Laravel Eloquent - many to many with where for the pivot table -
I am trying to see what is the best way to do the following:
My There are 3 tables: users, items, and item_j
Users and items in the table contain generic, id and some columns that hold data.
The item_using table has the following structure id- item_id
user_id
user_type [1 - owner | 2 - Followers | 3 - Something else]
Relationships: Each item has 1 owner (user type) - each item has many followers - Each user can do many items themselves
Each user follows several items
I want the owner and followers to be the user table, so I do not have to repeat the user data. I created a pivot table of item_id, user_id and user_type to capture these relationships.
So the question is how am I doing this in Laravel Eloquent?
The item looks like a model:
public function user () {return $ this- & gt; Affiliation ('user'); // This is not true right because it is related to only one user, but it is not certain how to specify that user_type = 1; // Return $ - THIS- & gt; Affiliation ('user'); }
User model looks like this:
public function items () {return $ this- & gt; Hammaman ('item'); }
Thanks!
You can just add a condition to your relatedness
announcement:
public function user () {return $ this- & gt; Affiliation Value ('Users') - & gt; Where ('user_type', 1); }
This will return only the user
entries that have user_type = 1
in your pivot table. And to make it more clear, you can name the method owner ()
instead of user ()
to reflect the added condition.
Comments
Post a Comment