Doctrine 2 DQL MySQL equivalent to ROUND()?

前端 未结 3 913
南笙
南笙 2020-12-19 04:35

I know from the documentation at: http://docs.doctrine-project.org/en/2.1/reference/dql-doctrine-query-language.html#dql-functions that there is no ROUND function but is the

3条回答
  •  轻奢々
    轻奢々 (楼主)
    2020-12-19 05:04

    A bit cleaner approach would be using slightly modified @Ocramius code.

    Put this piece of code in: src/YourNamespace/YourMainBundle/DoctrineFunctions/ directory as the Round.php filename:

    getLexer();
    
            $parser->match(Lexer::T_IDENTIFIER);
            $parser->match(Lexer::T_OPEN_PARENTHESIS);
    
            $this->arithmeticExpression = $parser->SimpleArithmeticExpression();
    
            $parser->match(Lexer::T_CLOSE_PARENTHESIS);
        }
    
        public function getSql(\Doctrine\ORM\Query\SqlWalker $sqlWalker)
        {
            return 'ROUND(' . $sqlWalker->walkSimpleArithmeticExpression($this->arithmeticExpression) . ')';
        }
    }
    

    Then put this in your app/config/config.yml:

    doctrine:
        dql:
            numeric_functions:
                round: YourApp\YourMainBundle\DoctrineFunctions\Round
    

    That would allow you to use the ROUND() function directly in your DQL SELECT queries; no matter if done with QueryBuilder or directly via createQuery()

提交回复
热议问题