而且......也许它会对某人有所帮助。回答:
//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()
完毕。