我正在尝试用他的查询计算返回的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
我无法获得与oj​​it_a不同的其他指针

最佳答案

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

关于php - 如何在Doctrine查询构建器(Symfony)中使用countDistinct,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/25138219/

10-09 22:07