Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Doctrine2 QueryBuilder: How to filter out entities having zero count for a OneToMany

In my Dymfony2 / Doctrine2 application, I have a oneToMany relation between an object and its children.

I want to select all objects which have no children.

I'm stuck with various errors: SingleValuedAssociationField expected, Cannot add Having sth on non result variable, etc.

$queryBuilder = $this
    ->createQueryBuilder('object')
    ->leftJoin('object.children', 'children')
    ->andWhere('children IS NULL')
    // tested with a parameter, with addselect COUNT(children) and 0 condition, etc.
    ->getQuery()
    ->getResult();

How can I solve this?

like image 921
Sébastien Avatar asked May 25 '15 19:05

Sébastien


1 Answers

There is a selector called SIZE(), which should do the trick. More to read here.

Try something like this:

$this
    ->createQueryBuilder('object')
    ->leftJoin('object.children', 'children')
    ->where('SIZE(object.children) = 0')
    ->getQuery()
    ->getResult();
like image 140
Artamiel Avatar answered Nov 15 '22 09:11

Artamiel