Laravel 多对多关系 - 检索模型
Laravel many to many relationships - retrieving models
如果我们有这样的事情:
用户
- id
- 姓名
角色
- id
- 姓名
店铺
- 编号
- 姓名
role_user
- role_id
- user_id
shop_user
- shop_id
- user_id
快速:商店---shop_user---用户---role_user---角色
并且我们希望 SHOP 1 的所有用户都具有管理员角色。我们该怎么做?
来自商店 1 的所有用户:
$shop = Shop::find( $shopId );
$shop->users()->get();
像这样就好了:
$shop = Shop::find( $shopId );
$shop->users()->roles->()->where( 'name', 'Admin' )->get();
使用whereHas()
方法:
$users = User::whereHas('roles', function($q) use($roleId) {
$q->where('id', $roleId)
})->whereHas('shops', function($q) use($shopId) {
$q->where('id', $shopId)
})->get();
假设你的人际关系如期进行,这应该会让你得到你想要的结果:
$shop = Shop::with(['users' => function ($q) {
$q->whereHas('roles', function ($q) {
$q->where('name', 'Admin');
});
}])->find($shopId);
它会 select 与 id = $shopId
一起购物,它会附加所有 users
,role
其中 roles.name = Admin
你得到这样的用户$users = $shop->users
如果我们有这样的事情:
用户
- id
- 姓名
角色
- id
- 姓名
店铺
- 编号
- 姓名
role_user
- role_id
- user_id
shop_user
- shop_id
- user_id
快速:商店---shop_user---用户---role_user---角色
并且我们希望 SHOP 1 的所有用户都具有管理员角色。我们该怎么做?
来自商店 1 的所有用户:
$shop = Shop::find( $shopId );
$shop->users()->get();
像这样就好了:
$shop = Shop::find( $shopId );
$shop->users()->roles->()->where( 'name', 'Admin' )->get();
使用whereHas()
方法:
$users = User::whereHas('roles', function($q) use($roleId) {
$q->where('id', $roleId)
})->whereHas('shops', function($q) use($shopId) {
$q->where('id', $shopId)
})->get();
假设你的人际关系如期进行,这应该会让你得到你想要的结果:
$shop = Shop::with(['users' => function ($q) {
$q->whereHas('roles', function ($q) {
$q->where('name', 'Admin');
});
}])->find($shopId);
它会 select 与 id = $shopId
一起购物,它会附加所有 users
,role
其中 roles.name = Admin
你得到这样的用户$users = $shop->users