Search code examples
phpsqlsymfonydoctrine-ormdql

Doctrine2 get join results when child is empty


I'm working with Doctrine2 in a Symfony2 project, where I'm trying to optimize queries and lazy loading.

I have two entities Parent and Child.

Now, if in my controller I retrieve an specific Parent and I pass it through a view (twig) all works fine, but when I want to show data related to Child Doctrine2 makes another query.

I've tried to make my own DQL to obtain all in only one query (an specific Parent with all of its Childs. All works good if a Parent has at least one Child, but if there's not any ChildI obtain a null result.

This is my DQL:

$dql = ' SELECT p, c
        FROM AppBundle:Parent p
        JOIN p.childs c
        WHERE p.id = :parentId
          AND c.state = :state';

Solution:

$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);

Solution

  • All you need is a left join instead of an inner join:

    SELECT p, c
        FROM AppBundle:Parent p
        JOIN p.childs c
        WHERE p.id = :parentId
          AND (c.state = :state or c.state is null)
    

    This will basically keep all results from the left table(in this case the parent table) and will keep only the matching results from the right table(the childs table)