amitsolanki24_'s avatar

hasmany vs belongs to many

When I should use hasmany or belongstomany relationship or hasone vs belongsto?

And what is the difference between hasmany vs belongs to many.

0 likes
4 replies
tykus's avatar

Use a hasMany relationship whenever there is a FK for the current Model on the related Model’s table. Model A has many Model B, Model B belongs to Model A

A belongsToMany relation is use whenever we need a pivot table. Model A has many Model B and Model B also has many Model A

1 like
tykus's avatar

@amitsolanki24_ there are myriad examples, e.g.

  • books loaned by users from a library: aBook is loaned by multiple User; a User is loaned multiple Book
  • products in an order: an Order is comprised of multiple Products; a Product is ordered on different Orders
  • students' class enrollments: a Class is taken by many Students; a Student takes multiple Class
  • ...
1 like

Please or to participate in this conversation.