在 Laravel 4.2 中,我试图实现一个返回所有具有所有特定活动的用户的查询。截至目前,我有一个查询返回所有具有许多活动之一的用户:
//$selectedActivities being an array
$userByActivities = User::with('activities')
->whereHas('activities', function($query) use($selectedActivities){
$query->whereIn('id', $selectedActivities);
})->get();
更清楚:给定的活动 a,b,c 。我正在寻找有活动 a AND b AND c 的所有用户。我的查询返回所有具有活动 a OR b OR c 的用户。
感谢您的帮助。
修改
lukasgeiter提供的解决方案导致以下查询:
select * from `users` where
(select count(*) from `activities` inner join `activity_user` on `activities`.`id` = `activity_user`.`activity_id` where `activity_user`.`user_id` = `users`.`id` and `id` = '7') >= 1
and (select count(*) from `activities` inner join `activity_user` on `activities`.`id` = `activity_user`.`activity_id` where `activity_user`.`user_id` = `users`.`id` and `id` = '3') >= 1
and (select count(*) from `activities` inner join `activity_user` on `activities`.`id` = `activity_user`.`activity_id` where `activity_user`.`user_id` = `users`.`id` and `id` = '1') >= 1
and (select count(*) from `activities` inner join `activity_user` on `activities`.`id` = `activity_user`.`activity_id` where `activity_user`.`user_id` = `users`.`id` and `id` = '2') >= 1
Jarek Tkaczyk提供的解决方案:
$userByActivities = User::with('activities')
->whereHas('activities', function($query) use($selectedActivities) {
$query->selectRaw('count(distinct id)')->whereIn('id', $selectedActivities);
}, '=', count($selectedActivities))->get();
对于类似的请求,会导致以下查询:
select * from `users` where (select count(distinct id) from `activities`
inner join `activity_user` on `activities`.`id` = `activity_user`.`activity_id`
where `activity_user`.`user_id` = `users`.`id` and `id` in ('7', '3', '1', '2')) = 4
答案 0 :(得分:8)
您必须为此添加多个whereHas
:
$query = User::with('activities');
foreach($selectedActivities as $activityId){
$query->whereHas('activities', function($q) use ($activityId){
$q->where('id', $activityId);
});
}
$userByActivities = $query->get();
答案 1 :(得分:0)
如果获取Cardinality violation: 1241 Operand should contain 2 column(s)
的问题是嵌套的selectCount
会添加到普通select count(*)
而不是覆盖现有选择,所以更改为$query->distinct()->whereIn('id', $selectedActivities);
可以解决此问题我,或更改为$query->select(DB::raw(count(distinct id)))