title: Laravel Eloquent - Where In All
body: <p>In <strong>Laravel 4.2</strong>, 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:</p>
  
  <pre><code>//$selectedActivities being an array
          $userByActivities = User::with('activities')
                  -&gt;whereHas('activities', function($query) use($selectedActivities){
                      $query-&gt;whereIn('id', $selectedActivities);
                  })-&gt;get();
  </code></pre>
  
  <p>To be more clear: given activities <em>a,b,c</em>. I am looking for all users that have activity <em>a AND b AND c</em>. My query returns all users that have activity <em>a OR b OR c</em>.</p>
  
  <p>Thank you for your help.</p>
  
  <p><strong>EDIT:</strong></p>
  
  <p>The solution offered by <a href="https://stackoverflow.com/users/1903366/lukasgeiter">lukasgeiter</a> results in following query:</p>
  
  <pre><code>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') &gt;= 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') &gt;= 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') &gt;= 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') &gt;= 1
  </code></pre>
  
  <p>Whereas the solution offered by <a href="https://stackoverflow.com/users/784588/jarek-tkaczyk">Jarek Tkaczyk</a>:</p>
  
  <pre><code>$userByActivities = User::with('activities')
   -&gt;whereHas('activities', function($query) use($selectedActivities) {
       $query-&gt;selectRaw('count(distinct id)')-&gt;whereIn('id', $selectedActivities);
   }, '=', count($selectedActivities))-&gt;get();
  </code></pre>
  
  <p>for a similar request, results in following query:</p>
  
  <pre><code>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
  </code></pre>