Reputation: 211
If we have something like this:
Quick: shop---shop_user---user---role_user---role
and we want all USER from SHOP 1 with ROLE admin. How can we do that?
all USER from SHOP 1:
$shop = Shop::find( $shopId );
$shop->users()->get();
Something like this would be nice:
$shop = Shop::find( $shopId );
$shop->users()->roles->()->where( 'name', 'Admin' )->get();
Upvotes: 3
Views: 132
Reputation: 163748
Use whereHas()
method:
$users = User::whereHas('roles', function($q) use($roleId) {
$q->where('id', $roleId)
})->whereHas('shops', function($q) use($shopId) {
$q->where('id', $shopId)
})->get();
Upvotes: -1
Reputation: 9942
Assuming your relationships work as intended, this should get you the result you want:
$shop = Shop::with(['users' => function ($q) {
$q->whereHas('roles', function ($q) {
$q->where('name', 'Admin');
});
}])->find($shopId);
It will select Shop with id = $shopId
and it will attach all users
to it, that have role
where roles.name = Admin
You get the users like this $users = $shop->users
Upvotes: 3