我有一个 users
表和 2 个数据透视表(user_locations
、user_roles
),允许用户与多个“位置”关联,并且“角色”。选择属于纽约
(位置)和经理
(角色)的用户的最佳方式是什么?
每个表中的列:
表用户
=> id
,名称
表user_locations
=> user_id
,location_id
表user_roles
=> user_id
,role_id
例如,我想获取与 location_id 100
和 role_id 200
关联的用户列表
我希望我能清楚地解释我的目标。预先感谢您!
最佳答案
如果您在用户模型中正确设置了关系,您可以执行以下操作:
$new_york_managers = User::whereHas('locations', function($q) {
$q->where('id', 100);
})->whereHas('roles', function($q) {
$q->where('id', 200);
});
关于MySQL/Laravel/ Eloquent : Select rows that exist in 2 tables,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44768151/