Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Doctrine Query Builder count ManyToMany

I have an entity Offer. Offer has a ManyToMany Relationship to Files. Now I want to have all Offers, that have files -> Count(offer.files) > 0.

I tried it like this, but doesn't work:

$this->repository->createQueryBuilder('offer')
            ->addSelect('COUNT(offer.files) as files')
            ->having('files > 1')
            ->getQuery()
            ->getResult();
like image 520
Zwen2012 Avatar asked Jan 01 '23 17:01

Zwen2012


1 Answers

Actually you do not need a join. Doctrine has built in SIZE DQL function for that.

SIZE(collection) - Return the number of elements in the specified collection

So you could use it like this:

$this->repository->createQueryBuilder('offer')
    ->addSelect('SIZE(offer.files) as files')
    ->having('files > 1')
    ->getQuery()
    ->getResult();
like image 197
Laurynas Avatar answered Jan 04 '23 17:01

Laurynas