How to use countDistinct in Doctrine query builder (Symfony)
Asked Answered
C

2

17

I am trying to count the distinct number of IDs returned for a query with his:

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

I am getting this error though:

Attempted to call method "countDistinct" on class "Doctrine\ORM\QueryBuilder" [...]

I have also tried

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

which leads to this error:

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

I can't get any other pointers as to how to do this differently from the documentation

Coach answered 5/8, 2014 at 11:55 Comment(0)
F
35

countDistinct is method of Expr class and COUNT DISTINCT need to be in SELECT statement so:

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

should work. Or simply:

$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();
Fungus answered 5/8, 2014 at 12:55 Comment(1)
Thanks, But how come DISTINCT works as a function when used with SUM but doesn't work the same with COUNT ? Any information ?Datura
R
3

Proper way to use countDistinct in your case is:

$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();
Retract answered 5/8, 2014 at 12:40 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.