Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Group By day and month Doctrine

I'd like to list my users by birthday, so month and day but not year.

I have this query

SELECT * 
FROM user 
WHERE birthDate IS NOT NULL 
GROUP BY MONTH(birthDate), DAY(birthDate)

But I don't know how to use it with Symfony and Doctrine. I tried

$result = $em->getRepository("AcmeApplicationBundle:SecurityServiceUser")
            ->createQueryBuilder('user')
            ->where('user.birthDate IS NOT NULL')
            ->groupBy('MONTH(user.birthDate), DAY(user.birthDate)')
            ->getQuery()
            ->getResult(); 

And

$result = $em->getRepository("AcmeApplicationBundle:SecurityServiceUser")
            ->createQueryBuilder('user')
            ->where('user.birthDate IS NOT NULL')
            ->groupBy('MONTH(user.birthDate)')
            ->groupBy('DAY(user.birthDate)')
            ->getQuery()
            ->getResult(); 

But in both cases I have an error

[Semantical Error] line 0, col 165 near 'MONTH(birthDate),': Error: Cannot group by undefined identification or result variable.

like image 724
Ajouve Avatar asked Mar 16 '14 21:03

Ajouve


1 Answers

You haven't set an alias for your values. Here is an updated version :

   $result = $em->getRepository("AcmeApplicationBundle:SecurityServiceUser")
        ->createQueryBuilder('user')
        ->select(' user.username, MONTH(user.birthDate) AS gBmonth, DAY(user.birthDate) AS gBday')
        ->where('user.birthDate IS NOT NULL')
        ->groupBy('gBmonth')
        ->addGroupBy('gBday')
        ->getQuery()
        ->getResult(); 

This should work fine.

like image 142
Charles-Antoine Fournel Avatar answered Nov 13 '22 09:11

Charles-Antoine Fournel