Symfony2:Doctrine MySql数学函数

时间:2015-08-01 19:50:07

标签: php mysql symfony doctrine-orm

我试着按年龄段计算人数。

AGEBRACKET | NBR
    10     |  3
    20     |  14
    30     |  123
    40     |  4
    50     |  55
...

这是我的代码:

$qb = $em->createQueryBuilder();
    $qb->select('FLOOR((YEAR(CURDATE())-YEAR(p.date_birth)) / 10) * 10 AS age, COUNT(p.id)');
    $qb->from('MyBundle:Person', 'p');
    $qb->groupBy('age');
    $countByAge = $qb->getQuery()->execute();

我收到此错误:

  

[语法错误]第0行,第7行:错误:预期已知函数,得到   'FLOOR'

我看一点解决方案,这就是我发现的:

<?php
namespace MyProject\Query\AST;

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

class MysqlFloor extends FunctionNode
{
    public $simpleArithmeticExpression;

    public function getSql(\Doctrine\ORM\Query\SqlWalker $sqlWalker)
    {
        return 'FLOOR(' . $sqlWalker->walkSimpleArithmeticExpression(
            $this->simpleArithmeticExpression
        ) . ')';
    }

    public function parse(\Doctrine\ORM\Query\Parser $parser)
    {
        $lexer = $parser->getLexer();

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

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

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

<?php
\Doctrine\ORM\Query\Parser::registerNumericFunction('FLOOR', 'MyProject\Query\MysqlFloor');
$dql = "SELECT FLOOR(person.salary * 1.75) FROM CompanyPerson person";

我得到另一个错误:

Attempted to call method "registerNumericFunction" on class "Doctrine\ORM\Query\Parser".

您知道如何才能获得理想的结果吗?

由于

2 个答案:

答案 0 :(得分:0)

Doctrine文档中的更新版本可以帮助您: http://doctrine-orm.readthedocs.org/en/latest/reference/dql-doctrine-query-language.html#adding-your-own-functions-to-the-dql-language

如果您想将其添加到Symfony配置中,以便可以在项目的任何位置使用它,请参阅http://symfony.com/doc/current/cookbook/doctrine/custom_dql_functions.html了解如何执行此操作。

答案 1 :(得分:0)

解决方案:

#config.yml
    orm:
        dql:
            numeric_functions:
                FLOOR: FrontBundle\DoctrineFunctions\FloorFunction
#FloorFunction.php
<?php
namespace MyBundle\DoctrineFunctions;

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

class FloorFunction extends FunctionNode
{
    public $simpleArithmeticExpression;

    public function getSql(\Doctrine\ORM\Query\SqlWalker $sqlWalker)
    {
        return 'FLOOR(' . $sqlWalker->walkSimpleArithmeticExpression(
            $this->simpleArithmeticExpression
        ) . ')';
    }

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

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

        $parser->match(Lexer::T_CLOSE_PARENTHESIS);
    }
}
$config = $em->getConfiguration();
$config->addCustomNumericFunction('FLOOR', 'MyBundle\DoctrineFunctions\FloorFunction');