如何在Doctrine Query Builder(Symfony)中使用CountDist

2022-09-04 00:00:00 php symfony doctrine-orm query-builder

我正在尝试计算使用HIS:

为查询返回的不同ID数
$query = $repo->createQueryBuilder('prov')
        ->select('c.id')
        ->innerJoin('prov.products', 'prod')
        ->innerJoin('prod.customerItems', 'ci')
        ->innerJoin('ci.customer', 'c')
        ->where('prov.id = :brand')
        ->setParameter('brand', $brand)
        ->countDistinct('c.id')
        ->getQuery();

我收到此错误:

Attempted to call method "countDistinct" on class "DoctrineORMQueryBuilder" [...]

我也试过

$query = $repo->createQueryBuilder('prov')
        ->select('c.id')
        ->innerJoin('prov.products', 'prod')
        ->innerJoin('prod.customerItems', 'ci')
        ->innerJoin('ci.customer', 'c')
        ->where('prov.id = :brand')
        ->setParameter('brand', $brand)
        ->expr()->countDistinct('c.id')
        ->getQuery();

导致此错误的原因:

Error: Call to a member function getQuery() on a non-object in

我找不到任何其他指示,说明如何与documentation

不同地执行此操作

解决方案

countDistinct是Expr类的方法,COUNT DISTINCT需要在SELECT语句中:

$qb = $repo->createQueryBuilder('prov');
$query = $qb
        ->select($qb->expr()->countDistinct('c.id'))
        ->innerJoin('prov.products', 'prod')
        ->innerJoin('prod.customerItems', 'ci')
        ->innerJoin('ci.customer', 'c')
        ->where('prov.id = :brand')
        ->setParameter('brand', $brand)
        ->getQuery();

应该行得通。 或者干脆:

$query = $repo->createQueryBuilder('prov')
        ->select('COUNT(DISTINCT c.id)')
        ->innerJoin('prov.products', 'prod')
        ->innerJoin('prod.customerItems', 'ci')
        ->innerJoin('ci.customer', 'c')
        ->where('prov.id = :brand')
        ->setParameter('brand', $brand)
        ->getQuery();

相关文章