MySQL/Laravel/Eloquent:选择存在于两个表中的行
问题描述:
我有一个users
表和两个数据透视表(user_locations
,user_roles
),它允许用户关联多个“位置”和“角色”。选择属于New York
(某个位置)的用户的最佳方式是什么?和Manager
(角色)?MySQL/Laravel/Eloquent:选择存在于两个表中的行
列在每个表中:
表users
=>id
,name
表user_locations
=>user_id
,location_id
表user_roles
=>user_id
,role_id
因此,例如,我想要获取与location_i关联的用户列表d 100
和role_id 200
我希望我明确地解释我的目标。先谢谢你!
答
如果您在用户模式有正确的关系设置,你可以这样做:
$new_york_managers = User::whereHas('locations', function($q) {
$q->where('id', 100);
})->whereHas('roles', function($q) {
$q->where('id', 200);
});
该诀窍。非常感谢! –