MySQL/Laravel/Eloquent:选择存在于两个表中的行

问题描述:

我有一个users表和两个数据透视表(user_locations,user_roles),它允许用户关联多个“位置”和“角色”。选择属于New York(某个位置)的用户的最佳方式是什么?Manager(角色)?MySQL/Laravel/Eloquent:选择存在于两个表中的行

列在每个表中:

users =>idname

user_locations =>user_idlocation_id

user_roles =>user_idrole_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); 
}); 
+0

该诀窍。非常感谢! –