Use a DATE() function in a WHERE clause with DQL

前端 未结 1 644
名媛妹妹
名媛妹妹 2020-12-01 16:48

I get a strange error when I execute this DQL query:

SELECT u FROM User u LEFT JOIN u.schedule s WHERE DATE(s.timestamp) = DATE(NOW())

The

相关标签:
1条回答
  • 2020-12-01 17:07

    You can achieve what you want by using a custom function:

    use Doctrine\ORM\Query\AST\Functions\FunctionNode;
    use Doctrine\ORM\Query\Lexer;
    use Doctrine\ORM\Query\SqlWalker;
    use Doctrine\ORM\Query\Parser;
    
    class DateFunction extends FunctionNode
    {
        private $arg;
    
        public function getSql(SqlWalker $sqlWalker)
        {
            return sprintf('DATE(%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);
        }
    }
    

    Then registering this function in your code:

    $em->getConfiguration()->addCustomDatetimeFunction('DATE', 'DateFunction');
    

    And your DQL query will work!

    0 讨论(0)
提交回复
热议问题