DavidBuchukuri's avatar

belongsToMany vs hasMany

I am working on a project and I don't really know which one to use hasMany or belongsToMany. I need to make comments section, where user can comment on a post. I checked my old project(I was following tutorial) where i implemented comments section, and there i used hasMany on user and post model. But on current project i wanted to make many to many relationship between movies and genres, and by following laravel's documentation, I implemented them with belongsToMany. what's the difference between hasMany and belongsToMany?

0 likes
2 replies
signorpiero's avatar
Level 3

If you need to make a one to many relationship (a user can make many comments and a comment is associated to only one user) you can use a hasMany. BelongsToMany is for many to many relationship (for example a user have many roles and a role is associated to many users).

5 likes

Please or to participate in this conversation.