title: Doctrine2: using the querybuilder for many-to-many relationships
body: <p>To search people in a system I have written a function in a repository.
  This function receives an array with field names and criteria, and uses the querybuilder to formulate a valid DQL-statement.</p>
  
  <p>Everything works fine, until the moment I want to make a search rule like:</p>
  
  <p>"Find all people that belong to a certain domain."</p>
  
  <p>...where the Person and Domain entities have a many-to-many relationship.</p>
  
  <p>According to Symfony2 that relationship is defined correctly, and indeed everything works in Twig templates and controllers.</p>
  
  <p>The function looks as follows:-</p>
  
  <pre><code>private function query($extra_conditions = null)
  {
  
      $qb = $this-&gt;_em-&gt;createQueryBuilder();
      $query =
      $qb-&gt;select('p')
      -&gt;from('AppMainBundle:Person', 'p')
      -&gt;leftjoin('AppMainBundle:Domain', 'd')
      -&gt;where("p.firstname IS NOT NULL")
      -&gt;andWhere("p.lastname IS NOT NULL")
      -&gt;andWhere("p.function IS NOT NULL");
  
      if ($extra_conditions!=null)
      {
          foreach ($extra_conditions as $condition)
          {
              #filter on firstname
                  if (key($condition)=='firstname')
                      $query = $query-&gt;andWhere('p.firstname LIKE ?1')
                      -&gt;setParameter(1, $condition['firstname']);
              #filter on lastname
                  if (key($condition)=='lastname')
                      $query = $query-&gt;andWhere('p.lastname LIKE ?1')
                      -&gt;setParameter(1, $condition['lastname']);
              #filter on gender
                  if (key($condition)=='gender')
                      $query = $query-&gt;andWhere('p.gender = '.$condition['gender']);
              #filter on domain(s)
                  if (key($condition)=='domains')
                      $query = $query-&gt;andWhere('d.id IN ('.$condition['domains'].')');
              #filter on town
                  if (key($condition)=='town')
                      $query = $query-&gt;andWhere('p.town LIKE ?1')
                      -&gt;setParameter(1, $condition['town']);
          }
      }
  
      $query = $query-&gt;orderBy("p.lastname", "ASC");
  
      $query = $qb-&gt;getQuery();
      return $query-&gt;getResult();
  }
  </code></pre>
  
  <p>There is no error, but whatever domains are given as search criteria; people from all domains are found and returned.</p>
  
  <p>Domains are provided as an array like (2, 4).</p>
  
  <p>What can I change to make it possible to find people belonging to certain domains?</p>