Doctrine 2 DQL MySQL 等价于 ROUND()?

2022-01-03 00:00:00 mysql doctrine-orm

我从以下文档中了解到:http://docs.doctrine-project.org/en/2.1/reference/dql-doctrine-query-language.html#dql-functions没有 ROUND 函数,但有没有一种简单的方法可以在不编写自己的 DQL 类函数的情况下做到这一点?

如果可以求平均值并返回整数,我就不需要完全匹配.

解决方案

你需要实现一个 自定义 DQL 函数.

DoctrineExtensions 中有一些示例.>

你可以像下面这样实现它:

walkSimpleArithmeticExpression($this->arithmeticExpression).')';}公共函数解析(DoctrineORMQueryParser $parser){$lexer = $parser->getLexer();$parser->match(Lexer::T_IDENTIFIER);$parser->match(Lexer::T_OPEN_PARENTHESIS);$this->arithmeticExpression = $parser->SimpleArithmeticExpression();$parser->match(Lexer::T_CLOSE_PARENTHESIS);}}

然后您可以在引导 ORM 时将其注册到配置中:

$config = new DoctrineORMConfiguration();$config->addCustomNumericFunction('ROUND', 'MyAppDQLRound');

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 there an easy way to do it without writing my own DQL class function?

Edit: I would not need an exact match if doing an average and returning a whole number is possible.

解决方案

You need to implement a custom DQL function for that.

There's some examples in DoctrineExtensions.

You can implement it like following:

<?php

namespace MyAppDQL;

use DoctrineORMQueryASTFunctionsFunctionNode;
use DoctrineORMQueryLexer;
use DoctrineORMQuerySqlWalker;

class Round extends FunctionNode
{
    private $arithmeticExpression;

    public function getSql(SqlWalker $sqlWalker)
    {

        return 'ROUND(' . $sqlWalker->walkSimpleArithmeticExpression(
            $this->arithmeticExpression
        ) . ')';
    }

    public function parse(DoctrineORMQueryParser $parser)
    {

        $lexer = $parser->getLexer();

        $parser->match(Lexer::T_IDENTIFIER);
        $parser->match(Lexer::T_OPEN_PARENTHESIS);

        $this->arithmeticExpression = $parser->SimpleArithmeticExpression();

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

You can then register it in the configuration while bootstrapping the ORM:

$config = new DoctrineORMConfiguration();

$config->addCustomNumericFunction('ROUND', 'MyAppDQLRound');

相关文章