学说2.2双重型到一种力量

时间:2012-10-17 12:12:51

标签: mysql doctrine-orm

在实体存储库中:

$qb = $this->createQueryBuilder('c');
//....
$qb->addSelect('POWER('.$qb->expr()->abs(
                $qb->expr()->diff('c.latitude', $filter['latitude'])
            ).',2) AS ddst';
//....
return $qb->getQuery(); //to Pagerfanta with DoctrineORMAdapter

错误:

QueryException: [Syntax Error] line 0, col 11: Error: Expected known function, got 'POWER'

QueryException: SELECT c, (POWER(ABS(c.delivery_latitude - 47.227163),2) AS ddst 
FROM MyEntity c ORDER BY ddst ASC, c.created_at DESC (this is dql error)

什么不对? Dql不支持POWER。我没有在qb-expressions中找到它。

3 个答案:

答案 0 :(得分:1)

而且......也许对某人有帮助。回答:

//app/config/config.yml

doctrine:
    dbal:
        #.....    
    orm:
        auto_generate_proxy_classes: %kernel.debug%
        # auto_mapping: true #comment this line if isset
        entity_managers:
            default:
                auto_mapping: true #from orm to here or custom mapping
                dql:
                    numeric_functions:
                        power: Acme\MyBundle\DQL\PowerFunction #or power_num: ... it's an identifier

的src / Acme公司/ MyBundle / DQL / PowerFunction.php:

<?php
namespace Acme\MyBundle\DQL;

use Doctrine\ORM\Query\Lexer;

class PowerFunction extends \Doctrine\ORM\Query\AST\Functions\FunctionNode
{
    public $numberExpression = null;
    public $powerExpression = 1;

    public function parse(\Doctrine\ORM\Query\Parser $parser)
    {
        //Check for correct
        $parser->match(Lexer::T_IDENTIFIER);
        $parser->match(Lexer::T_OPEN_PARENTHESIS);
        $this->numberExpression = $parser->ArithmeticPrimary();
        $parser->match(Lexer::T_COMMA);
        $this->powerExpression = $parser->ArithmeticPrimary();
        $parser->match(Lexer::T_CLOSE_PARENTHESIS);
    }

    public function getSql(\Doctrine\ORM\Query\SqlWalker $sqlWalker)
    {
        return 'POWER(' .
            $this->numberExpression->dispatch($sqlWalker) . ', ' .
            $this->powerExpression->dispatch($sqlWalker) . ')';
    }
}

使用(在MyEntityRepository中):

$qb = $this->createQueryBuilder('c');
//some code
$qb->addSelect('power('.$yourNumber.',2) AS powered_num');
//'power' must be in lowercase!!!; if idetifier in config for example, 'power_num', then write 'power_num($yournumber,2)'

//some code ...

return $qb->getQuery(); //or getResult()

进行。

答案 1 :(得分:1)

由于这个Bundle,我修复了同样的问题:

https://github.com/orocrm/doctrine-extensions

以下是处理方式。

1)安装库:

composer require oro/doctrine-extensions

2)将DQL函数添加到doctrine config:

doctrine:
    orm:
        dql:
            numeric_functions:
                pow: Oro\ORM\Query\AST\Functions\Numeric\Pow

这就是全部。

现在Doctrine知道如何处理SQL POW函数。

答案 2 :(得分:0)

DQL不是SQL。它不支持很多比较模糊的SQL函数,比如POWER。

如果需要,可以创建本机SQL查询。有关详细信息,请参阅此文档:

http://docs.doctrine-project.org/projects/doctrine-orm/en/latest/reference/native-sql.html