如何在 Doctrine 查询生成器 (Symfony) 中使用 countDistinct

2022-08-30 23:03:17

我正在尝试用他的来计算为查询返回的不同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 "Doctrine\ORM\QueryBuilder" [...]

我也试过

$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

我无法获得任何其他关于如何以不同于文档的方式执行此操作的指针


答案 1

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();

答案 2

在您的案例中,正确的使用方法是:countDistinct

$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();

推荐