3
votes

If we have something like this:

user

  • id
  • name

role

  • id
  • name

shop

  • id
  • name

role_user

  • role_id
  • user_id

shop_user

  • shop_id
  • user_id

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();
2

2 Answers

3
votes

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

-1
votes

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();