9
votes

In Laravel 4.2, I am trying to achieve a query that returns all users, that have all of certain activities. As of now, I have a query that returns all users that have one of many activities:

//$selectedActivities being an array
        $userByActivities = User::with('activities')
                ->whereHas('activities', function($query) use($selectedActivities){
                    $query->whereIn('id', $selectedActivities);
                })->get();

To be more clear: given activities a,b,c. I am looking for all users that have activity a AND b AND c. My query returns all users that have activity a OR b OR c.

Thank you for your help.

EDIT:

The solution offered by lukasgeiter results in following query:

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

Whereas the solution offered by Jarek Tkaczyk:

$userByActivities = User::with('activities')
 ->whereHas('activities', function($query) use($selectedActivities) {
     $query->selectRaw('count(distinct id)')->whereIn('id', $selectedActivities);
 }, '=', count($selectedActivities))->get();

for a similar request, results in following query:

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
2
The solution proposed by Jarek Tkaczyk is far more optimized than the accepted oneM Khalid Junaid

2 Answers

18
votes

You'll have to add multiple whereHas for that:

$query = User::with('activities');
foreach($selectedActivities as $activityId){
    $query->whereHas('activities', function($q) use ($activityId){
        $q->where('id', $activityId);
    });
}
$userByActivities = $query->get();
4
votes

If you are getting Cardinality violation: 1241 Operand should contain 2 column(s) the problem is the nested selectCount adds to the normal select count(*) instead of overriding the existing select, so changing to $query->distinct()->whereIn('id', $selectedActivities); did the trick for me, or changing to $query->select(DB::raw(count(distinct id)))