Skip to main content
Lennu.net

Doctrine Find out if Collection is Empty or Not

You can do a Doctrine query based on the amount of relationship/collection size fairly easy.

Usually in these cases you want to find out if some collection that’s related to your Entity has anything or is empty.

You can use the Query Builder’s where clause to limit these results.

Let’s say we have Category Entity and Product Entity. We want to fetch all Categories that have products.

<?php
 
namespace AppBundle\Repository;
 
class CategoryRepository extends \Doctrine\ORM\EntityRepository
{
    public function findCategoriesWithProducts() {
        $qb = $this->createQueryBuilder('c')
        ->where('SIZE(c.products) > 0');
        return $qb->getQuery()->getResult();
    }
}

See we are using SIZE to create the amount of products inside the category and fetching only the categories that have more than 0 products.