Reputation: 68
I have four tables:
Users: id, username
Roles: id, name
Domains id, title
DomainsAssignedRolesUsers id, role_id, user_id, domain_id
I want to get all user roles for a domain.
I do:
User::find(1)->domains->first()->roles
But i get all domains roles, not only for my user. Help me to get user roles only for the selected domain/
My relations:
// User model:
public function rolesDomain() {
return $this->belongsToMany('Role', 'domainsAssignedRolesUsers', 'user_id', 'role_id');
}
public function domains() {
return $this->belongsToMany('Domain', 'domainsAssignedRolesUsers');
}
// Role model:
public function domains() {
return $this->belongsToMany('Domain', 'domainsAssignedRolesUsers');
}
// Domain model:
public function roles() {
return $this->belongsToMany('Role', 'domainsAssignedRolesUsers', 'domain_id', 'role_id');
}
public function users() {
return $this->belongsToMany('User', 'domainsAssignedRolesUsers', 'domain_id', 'user_id');
}
Upvotes: 1
Views: 172
Reputation: 2757
You want to get all the roles, from a specific domain, in relation with an user?
So this should do the trick:
User::find(1)->rolesDomain()->where('domain_id', $specificID)->get()
But if you want to only get the roles from the first domain for an user.
User::find(1)->domains()->first()->roles()->get();
And if you only want to retrieve the roles for a user.
User::find(1)->rolesDomain()->get()
And if you only want to retrieve all the roles from each domain in relation with an user.
User::find(1)->domains()->with('roles')->get()
Even if Eloquent documentation has a few example, This orm is really intuitive.
Upvotes: 1
Reputation: 15802
Check out Eloquent Triple Pivot (also on Packagist), it sounds like it does exactly what you want.
You'd set up your Models as User
, Domain
and Role
(a User
has many Domain
s and can have a Role
in each). Then look at the docs on the Github page (particularly step 6), and you'd define this on your Domain
model:
class Domain extends Eloquent {
...
public function getRolesAttribute() {
return $this->getThirdAttribute();
}
}
Then you can simply call
$user = User::find(1);
$domain = $user->domains->first();
// or
$domain = $user->domains->find(73);
$roles = $domain->roles;
// Or the above can be condensed into just...
$roles = User::findOrFail( 1 )
->domains()
->findOrFail( 73 )
->roles;
Upvotes: 0