Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Doctrine 2 select count groupBy

I'm trying to retrieve a number of rows with unique uids.

$qb->select('COUNT() as cnt')
            ->from($type, 'c')
            ->groupBy('c.organization, c.process_role, c.domain, c.year')
            ->getQuery()->getSingleScalarResult()

But it returns an array of group counts. How should I write this correct?

Finally, that works, but it's kinda ugly

$count = $this->_em->createQuery( 'SELECT COUNT(c.id) FROM '.$type.' as c WHERE c.id IN ('
            . 'SELECT c1.id FROM ' . $type . ' c1 '
            . 'GROUP BY c1.organization, c1.process_role, c1.domain, c1.year)')
            ->getSingleScalarResult();
like image 677
Kamil Avatar asked Oct 30 '14 15:10

Kamil


People also ask

What is a QueryBuilder in doctrine 2?

The QueryBuilder — Doctrine 2 ORM 2 documentation 15. The QueryBuilder ¶ A QueryBuilder provides an API that is designed for conditionally constructing a DQL query in several steps. It provides a set of classes and methods that is able to programmatically build queries, and also provides a fluent API.

How to bind parameters to a query in doctrine?

Doctrine supports dynamic binding of parameters to your query, similar to preparing queries. You can use both strings and numbers as placeholders, although both have a slightly different syntax. Additionally, you must make your choice: Mixing both styles is not allowed. Binding parameters can simply be achieved as follows:

Can you use placeholders in Doctrine Query?

Binding parameters to your query ¶ Doctrine supports dynamic binding of parameters to your query, similar to preparing queries. You can use both strings and numbers as placeholders, although both have a slightly different syntax. Additionally, you must make your choice: Mixing both styles is not allowed.


1 Answers

Try breaking up your single groupBy into addGroupBy functions:

$qb->select('COUNT(c) as cnt')
            ->from($type, 'c')
            ->groupBy('c.organization')
            ->addGroupBy('c.process_role')
            ->addGroupBy('c.domain')
            ->addGroupBy('c.year')
            ->getQuery()->getSingleScalarResult();

However this does in fact return the same thing since it will just group results into unique sets by those 4 variables. You should instead use a DISTINCT selection method and count the resulting rows.

$rows = $this->getDoctrine()->getManager()
    ->createQuery(
        'SELECT DISTINCT c.organization, c.process_role, c.domain, c.year FROM ' . $type . ' c'
    )
    ->getArrayResult();
$count = count($rows);

This is the only known method to me that will work since DQL won't support any alternative strategies (such as SELECT COUNT(*) FROM (SELECT DISTINCT ... ))

like image 170
sjagr Avatar answered Sep 21 '22 07:09

sjagr