Doctrine Query Builder 计数 ManyToMany

Doctrine Query Builder count ManyToMany

我有实体要约。 Offer 与文件具有多对多关系。 现在我想要所有有文件的优惠 -> Count(offer.files) > 0.

我这样试过,但是不行:

$this->repository->createQueryBuilder('offer')
            ->addSelect('COUNT(offer.files) as files')
            ->having('files > 1')
            ->getQuery()
            ->getResult();

您需要 inner join with the association and group by 根实体报价:

->innerJoin('offer.files', 'files')

The INNER JOIN keyword selects records that have matching values in both tables.

那么您可以:

->addSelect('COUNT(files) as total')
->having('total > 1')
->groupBy('offer')

如果不需要结果中的总数,可以定义为HIDDEN,把上面第一行改成:

->addSelect('COUNT(files) as HIDDEN total')

Inner join in detail Doctrine query builder

实际上您不需要加入。为此,Doctrine 内置了 SIZE DQL function

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

所以你可以这样使用它:

$this->repository->createQueryBuilder('offer')
    ->addSelect('SIZE(offer.files) as files')
    ->having('files > 1')
    ->getQuery()
    ->getResult();