Query with EXISTS for Doctrine Symfony2
Asked Answered
W

1

24

How can I implement the following query with Query Builder?

SELECT * 
FROM t 
WHERE t.status = 1
    OR EXISTS(SELECT * 
              FROM r 
              WHERE r.t_id = t.id 
                  AND r.status = 1
             )

The part without exist check is easy, but is there a way to implement the EXISTS?

Wardieu answered 5/4, 2012 at 14:28 Comment(0)
E
38

You either need to use two query builders:

$queryBuilder->expr()->exists($subQueryBuilder->getDql());

or use DQL directly:

$queryBuilder->expr()->exists('SELECT * 
    FROM r 
    WHERE r.t_id = t.id 
    AND r.status = 1'
);

You'll find more examples in the docs: http://www.doctrine-project.org/projects/doctrine-orm/en/current/reference/query-builder.html


Note regarding parameters:

You have to set parameters in the main query, even though they're used in the exists (Thanks Vadim Ashikhman).

Eury answered 5/4, 2012 at 15:48 Comment(2)
Is it possible to bind parameters in the subquery? (your link is dead)Elagabalus
You have to set parameters in the main query even those that are used in the exists statement.Responsum

© 2022 - 2024 — McMap. All rights reserved.