Doctrine2 get join results when child is empty
<p>I'm working with Doctrine2 in a Symfony2 project, where I'm trying to optimize queries and lazy loading.</p>
<p>I have two entities <code>Parent</code> and <code>Child</code>.</p>
<p>Now, if in my controller I retrieve an specific <code>Parent</code> and I pass it through a view (twig) all works fine, but when I want to show data related to <code>Child</code> Doctrine2 makes another query.</p>
<p>I've tried to make my own <code>DQL</code> to obtain all in only one query (an specific <code>Parent</code> with all of its <code>Child</code>s. All works good if a <code>Parent</code> has at least one <code>Child</code>, but if there's not any <code>Child</code>I obtain a null result.</p>
<p>This is my <code>DQL</code>:</p>
<pre><code>$dql = ' SELECT p, c
        FROM AppBundle:Parent p
        JOIN p.childs c
        WHERE p.id = :parentId
          AND c.state = :state';
</code></pre>
<hr />
<h3>Solution:</h3>
<pre><code>$dql = 'SELECT p, c
            FROM AppBundle:Parent p
            LEFT JOIN p.childs c
            WHERE p.id = :parentId
              AND (c.state = :state' or c.state is null);
</code></pre>