Error when use custom DQL function with Doctrine and Symfony2

前端 未结 2 1655
萌比男神i
萌比男神i 2021-02-03 10:36

I use Symfony 2 and the ORM Doctrine. I want to create and register a custom DQL function. In fact, I want to use the SQL function \"CAST\" in my request, like this :

         


        
2条回答
  •  佛祖请我去吃肉
    2021-02-03 11:24

    After several search, I have finally found the solution. I had two problems: first my parse function was wrong, second, I called a SQL function in my orderBy (thank you Cerad).

    So, here is my correct class:

    namespace Ypok\YPoliceBundle\DQL;
    
    use Doctrine\ORM\Query\AST\Functions\FunctionNode;
    use Doctrine\ORM\Query\Lexer;
    use Doctrine\ORM\Query\SqlWalker;
    use Doctrine\ORM\Query\Parser;
    
    class CastFunction extends FunctionNode
    {
        public $firstDateExpression = null;
        public $unit = null;    
    
        public function parse(\Doctrine\ORM\Query\Parser $parser)
        {
            $parser->match(Lexer::T_IDENTIFIER);
            $parser->match(Lexer::T_OPEN_PARENTHESIS);
            $this->firstDateExpression = $parser->StringPrimary();
    
            $parser->match(Lexer::T_AS);
    
            $parser->match(Lexer::T_IDENTIFIER);
            $lexer = $parser->getLexer();
            $this->unit = $lexer->token['value'];
    
            $parser->match(Lexer::T_CLOSE_PARENTHESIS);
        }
    
        public function getSql(\Doctrine\ORM\Query\SqlWalker $sqlWalker)
        {
            return sprintf('CAST(%s AS %s)',  $this->firstDateExpression->dispatch($sqlWalker), $this->unit);
        }
    }
    

    And now, I can use perfectly the SQL function 'CAST' in my repository:

    $qb = $this->_em->createQueryBuilder();
    $qb->select('d, CAST(d.myField AS UNSIGNED) AS sortx')
       ->from('\Test\MyBundle\Entity\MyEntity', 'd')
       ->orderBy('sortx', 'ASC')
    
    return $qb->getQuery()->getResult();
    

    Best regards

提交回复
热议问题