ORM – many relationships in laravel: belongstomany() vs. hasmanythrough()
What is the difference between using belongstomany() or hasmanythrough() when defining many to many relationships in laravel?
Example: user account_ User
Therefore, the user passes the account_ The user table has many relationships with the account In addition to defining a PivotTable report for related users with related accounts, it also stores an account_ User. Role field, which determines the role of a given user in a given account
Use user belongstomany() account or user hasmanythrough() account_ What is the impact of user? Or is this essentially the same?
When deciding on a method, I think I should use the same method to define the reverse relationship
Solution
Suppose you have two models, let's call a and B:
If a may have multiple B projects, and if B may have multiple a projects (imagine blog posts / tags), you must use belongstomany();
Now let's suppose you have three models, a, B and C
A is related to B, B is related to C However, if you need to access all C related to a (above B), you need to use hasmanythrough() (imagine country – > users – > posts, you need all posts from a specific country / region)
Hasmanythrough () doesn't exactly mean many relationships, it's more like a shortcut
Check the document link, 1,2 (laravel 4.2) or 3,4 (laravel 5. X)