title: Doctrine 2.1 DQL - Many-to-many query multiple values - Item in multiple categories?
body: <p>This may seem like a rudimentary request, but I can't seem to get it to work, so I'm either missing something stupid, or am not understanding how it should be done. Thanks in advance.</p>
  
  <p>I have two doctrine entities with a many-to-many relationship: Items and Categories. Which are joined by items_has_categories.</p>
  
  <pre><code>/**
  * Item
  *
  * @Table(name="items")
  * @Entity(repositoryClass="Entity\Repository\Item")
  */
  class Item
  {
  
  ....
  
   /**
   * @var Categories
   *
   * @ManyToMany(targetEntity="Categorie", inversedBy="items", cascade={"persist"})
   * @JoinTable(name="items_has_categories",
   *   joinColumns={
   *     @JoinColumn(name="items_id", referencedColumnName="id")
   *   },
   *   inverseJoinColumns={
   *     @JoinColumn(name="categories_id", referencedColumnName="id")
   *   }
   * )
   */
  private $categories;
  
  ....
  }
  
  /**
  * Categorie
  *
  * @Table(name="categories")
  * @Entity(repositoryClass="Entity\Repository\Categorie")
  */
  class Categorie
  {
   .....
  
  /**
   * @var Items
   *
   * @ManyToMany(targetEntity="Item", mappedBy="categories")
   */
  private $items;
  
  ....
  }
  </code></pre>
  
  <p>And what I'm trying to do is run a query to return all items that are in all of "x" number of categories - which I think/thought should be a SELECT with and AND clause:</p>
  
  <pre><code>class Item extends EntityRepository
  {
      public function findItemsByCategories($categories)
      {
  
      $qString = 'SELECT j, t, c FROM Technique\Entity\Item j LEFT JOIN j.itemImages t JOIN j.categories c WHERE';
  
      $i = 0;
      foreach ($categories as $c)
      {
          $qString .= ' c.name = ?' . $i;
  
          if ($i &lt; (count($categories)-1))
          {
              $qString .= ' AND';
          }
          $i++;
      }
  
      $query = $this-&gt;_em-&gt;createQuery($qString);
      $query-&gt;setParameters($categories);
  
      return $query-&gt;getResult();
  }
  </code></pre>
  
  <p>That little bit of code has no errors and spits out the following DQL SELECT query (when 2 categories are sent in the array: $categories):</p>
  
  <pre><code>SELECT j, t, c FROM Technique\Entity\Item j LEFT JOIN j.itemImages t JOIN j.categories c WHERE c.name = ?0 AND c.name = ?1
  </code></pre>
  
  <p>This is always returning an empty array, i.e., no results. Even though in my DB, there are more than 20 items fitting the criteria: are in both categories.</p>
  
  <p>Anyone see what I'm doing wrong here? Is this supposed to be an AND selection...? Basically I'd just like to know how to query a many-to-many relationship in Doctrine 2+, where there's more than one value that must be met...</p>