Let’s say I have a posts and users models, I want to manage the relationship between them like so:
- bookmarks (A post can be bookmarked by many users and vice-verca)
- likes (Same idea as bookmarks)
The convention is to make a pivot table named post_user but in this case we have two so do I make two tables one for each relationships or is there a way to put both relationships in the same table.
I also would like to follow laravel conventions as much as possible so naming the pivot something other than post_user sounds like a bad idea
I obviously can’t make two tables both with the same name so that’s out of the question
2
Answers
You don’t have to make two tables, in laravel conventions you can add more columns to the pivot table, here is an example:
In Post model:
In User model:
Then you can fill it like the following:
Yes you can achieve both relationships in the same table.
When you create pivot table
post_user
you can have add atype
column to indicate the relationship type.Post Model would be
Here you are using a single pivot table but differentiating between "bookmarks" and "likes" based on the type column’s value and also maintaining Laravel conventions but this can be done with 2 pivot tables as well. Depends upon how you want to handle it.