Maybe I'm implementing wrong. Maybe I'm doing things I'm not supposed to do, but conceptually I think I'm okay.
I have two models, one is Users
, other is Communities
, and since it is a many to many relationship I need an intermediate table, Laravel calls them a pivot table. According to Laravel recommendations it is named communities_users
Normally, the pivot tables only contain the id's to the main tables. But I need a bit more data. Check this image, the migrations are done to match this diagram:
Here I have a role
in the pivot table. Lets say a user belongs to two communities, one as community's president, other as a member.
Of course the president
will have more capabilities than the member
, for example, he can accept a pending
person to become a member
person, or he can promote a member to a deputy
status or so...
Now lets say I want to get the names of the people with deputy
role on a given community. I can easily do that using the Query Builder, by joining the three tables and applying where('communities_users.role', 'deputy')
,
Now, what if I want to use the ORM and get the whole User
model?
I'd like to have a function on the Community so it gives me the users
of a given role
, maybe:
public function users($role) {
...
}
So I can do things like:
$community = Community::find($id);
foreach ($community->users('deputy') as user) {
...
echo user->name; // or whatever
...
}
Is it possible? How?
Hiding under the Many To Many section of the Eloquent relationship docs:
Filtering Relationships Via Intermediate Table Columns
You can also filter the results returned by
belongsToMany
using thewherePivot
andwherePivotIn
methods when defining the relationship:
return $this->belongsToMany('App\Role')->wherePivot('approved', 1);
return $this->belongsToMany('App\Role')->wherePivotIn('priority', [1, 2]);
Assuming your Communities model already has a belongsToMany
relationship set up for Users, you should be able to do something like:
$deputies = $community->users()
->wherePivot('role', 'deputy') // or equivalent value
->get();
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments