I'm trying to group my entity by a field (year) and do a count of it.
Code:
public function countYear()
{
$qb = $this->getEntityManager()->createQueryBuilder();
$qb->select('b.year, COUNT(b.id)')
->from('\My\Entity\Album', 'b')
->where('b.year IS NOT NULL')
->addOrderBy('sclr1', 'DESC')
->addGroupBy('b.year');
$query = $qb->getQuery();
die($query->getSQL());
$result = $query->execute();
//die(print_r($result));
return $result;
}
I can't seem to say COUNT(b.id) AS count
as it gives an error, and
I do not know what to use as the addOrderby(???, 'DESC')
value?
Please try this code for ci 2 + doctrine 2
If you want your Repository method to return an Entity you cannot use
->select()
, but you can use->addSelect()
with a hidden select.$qb = $this->createQueryBuilder('q') ->addSelect('COUNT(q.id) AS HIDDEN counter') ->orderBy('counter'); $result = $qb->getQuery()->getResult();
$result
will be an entity class object.what is the error you get when using
COUNT(b.id) AS count
? it might be becausecount
is a reserved word. tryCOUNT(b.id) AS idCount
, or similar.alternatively, try
$qb->addOrderby('COUNT(b.id)', 'DESC');
.what is your database system (mysql, postgresql, ...)?
There are many bugs and workarounds required to achieve order by expressions as of v2.3.0 or below:
The order by clause does not support expressions, but you can add a field with the expression to the select and order by it. So it's worth repeating that Tjorriemorrie's own solution actually works:
Doctrine chokes on equality (e.g.
=
,LIKE
,IS NULL
) in the select expression. For those cases the only solution I have found is to use a subselect or self-join:To suppress the additional field from the result, you can declare it
AS HIDDEN
. This way you can use it in the order by without having it in the result.