How can I use SQL's YEAR(), MONTH() and DAY() in Doctrine2?

You can add Doctrine extension so you can use the MySql YEAR and MONTH statement by adding this configuration if you're on Symfony:

doctrine:
    orm:
        dql:
            string_functions:
                MONTH: DoctrineExtensions\Query\Mysql\Month
                YEAR: DoctrineExtensions\Query\Mysql\Year

now you can use the MONTH and YEAR statements in your DQL or querybuilder.

Note: The extension supports MySQL, Oracle, PostgreSQL and SQLite.


In Symfony 4 you must install DoctrineExtensions:

composer require beberlei/DoctrineExtensions

And then edit the doctrine config file (config/packages/doctrine.yaml) as follow:

doctrine:
    orm:
        dql:
            string_functions:
                MONTH: DoctrineExtensions\Query\Mysql\Month
                YEAR: DoctrineExtensions\Query\Mysql\Year

For Symfony 4:

  1. Install: composer require beberlei/doctrineextensions
  2. Edit: config\packages\doctrine.yaml
    doctrine:
        orm:
            dql:
                datetime_functions:
                    DAY: DoctrineExtensions\Query\Mysql\Day
                    MONTH: DoctrineExtensions\Query\Mysql\Month
                    YEAR: DoctrineExtensions\Query\Mysql\Year
  1. Edit your controller:
    public function somex()
    {
        $em = $this->getDoctrine()->getManager();

        $emConfig = $em->getConfiguration();
        $emConfig->addCustomDatetimeFunction('YEAR', 'DoctrineExtensions\Query\Mysql\Year');
        $emConfig->addCustomDatetimeFunction('MONTH', 'DoctrineExtensions\Query\Mysql\Month');
        $emConfig->addCustomDatetimeFunction('DAY', 'DoctrineExtensions\Query\Mysql\Day');

        $day = '22';
        $month = '4';

        $qb = $em->createQueryBuilder()
            ->select('u')
            ->from('App\Entity\User', 'u')
            ->where('DAY(u.somedate) = :day')
            ->andwhere('MONTH(u.somedate) = :month')
            ->setParameter('month', $day)
            ->setParameter('day', $month)
        ;
        $trab = $qb->getQuery()->getResult();


        return $this->render('intranet/somex.html.twig', [
            'trab' => $trab
        ]);
    }
    ````