title: Doctrine 2 in Symfony 2 - Filtering a QueryBuilder by an association
body: <p>I have my two classes <code>User</code> and <code>Role</code>, and I need to make a <code>QueryBuilder</code> which returns a query for the users who have the <code>ROLE_PROVIDER</code> role. I need this for an entity form field in Symfony 2. In the Form Class definition I have the following snippet for the mentioned field:</p>
  
  <pre><code>$builder-&gt;add('provider', 'entity', array(
      'class'    =&gt; 'ElCuadreAccountBundle:User',
      'property' =&gt; 'username',
      'query_builder' =&gt; function(UserRepository $ur) {
                           return $ur-&gt;getUsersByRoleQB('ROLE_PROVIDER');
                         },
      'required' =&gt; true,
  ));
  </code></pre>
  
  <p>And then in my Custom <code>UserRepository</code> I have the following function, which should return a <code>QueryBuilder</code> object:</p>
  
  <pre><code>public function getUsersByRoleQB($role) {
      $qb = $this-&gt;createQueryBuilder('u');
      return $qb-&gt;join('u.roles','r')
                -&gt;where($qb-&gt;expr()-&gt;in('r.role',$qb-&gt;expr()-&gt;literal($role)))
                -&gt;orderBy('u.username', 'ASC');
  }
  </code></pre>
  
  <p>Of course this doesn't work, but i pasted it to illustrate my needs.</p>
  
  <p>I've been looking around and it seems Doctrine2 does not support natively filtering by an association. In <a href="http://docs.doctrine-project.org/projects/doctrine-orm/en/2.1/reference/faq.html">this page</a> they say so, and suggest using <code>DQL</code> for this kind of filtering. My problem is that I have not found how to make a <code>QueryBuilder</code> object from a <code>DQL</code> sentence. If you could also provide me with the right <code>DQL</code> query, I would be very grateful...</p>
  
  <p>Thanks for your help!</p>