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

时间:2014-08-05 11:55:48

标签: symfony doctrine-orm query-builder

我正在尝试用他的:

计算为查询返回的不同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

我无法从文档中获得有关如何执行此操作的任何其他指示。

有人可以提出解决方案吗?enter link description here

2 个答案:

答案 0 :(得分:23)

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

答案 1 :(得分: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();