Haseena P A
Haseena P A

Reputation: 17406

YEAR function is not Working in Symfony 2

Not able to use YEAR() in symfony 2 doctrine..My code is given below

   $users = $this->getEntityManager()
               ->createQuery("SELECT YEAR(u.dob) from AcmeDemoBundle:AppUsers u")
               ->getResult();

While running this code,it shows the following error

[Syntax Error] line 0, col 7: Error: Expected known function, got 'YEAR'

Why this happen ??

Upvotes: 2

Views: 1198

Answers (2)

Ahmed Siouani
Ahmed Siouani

Reputation: 13891

The mapping for this function (and many others for managing datetime elements) does not exist in doctrine. You've to use DoctrineExtensions and add the following mapping to your configuration,

# Doctrine Configuration
doctrine:
    orm:
        dql:
            datetime_functions:
                year: DoctrineExtensions\Query\Mysql\Year

You can also map it to a function of your own with a bit of more work.

Upvotes: 4

waldek_h
waldek_h

Reputation: 930

Add custom function to doctrine for example:

<?php
namespace Project\CustomBundle\Dql;

use Doctrine\ORM\Query\AST\Functions\FunctionNode;
use Doctrine\ORM\Query\Lexer;
use Doctrine\ORM\Query\SqlWalker;
use Doctrine\ORM\Query\Parser;

class YearFunction extends FunctionNode
{
    private $arg;

    public function getSql(SqlWalker $sqlWalker)
    {
        return sprintf('YEAR(%s)', $this->arg->dispatch($sqlWalker));
    }

    public function parse(Parser $parser)
    {
        $parser->match(Lexer::T_IDENTIFIER);
        $parser->match(Lexer::T_OPEN_PARENTHESIS);

        $this->arg = $parser->ArithmeticPrimary();

        $parser->match(Lexer::T_CLOSE_PARENTHESIS);
    }
}

in config.yml doctrine section

#config.yml

doctrine:
  orm:
    ...
    dql:
      datetime_functions:
        year: Project\CustomBundle\DqlYearFunction

Upvotes: 0

Related Questions