根据官方解释,我想创建我的自定义MySQL函数ROUND(),它可以采用(非强制性的)另一个第二个参数。
Sor far我做到了这一点:
<?php
namespace HQF\Bundle\PizzasBundle\DQL;
use \Doctrine\ORM\Query\AST\Functions\FunctionNode;
use \Doctrine\ORM\Query\Lexer;
class MysqlRound extends FunctionNode
{
public $simpleArithmeticExpression;
public function getSql(\Doctrine\ORM\Query\SqlWalker $sqlWalker)
{
return 'ROUND(' . $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);
}
}
但是如何实现ROUND(XX)
没问题,ROUND(XX, YY)
也可以呢?
答案 0 :(得分:11)
您需要声明第二个参数,并使用Lexer
,如下所示:
namespace HQF\Bundle\PizzasBundle\DQL;
use \Doctrine\ORM\Query\AST\Functions\FunctionNode;
use \Doctrine\ORM\Query\Lexer;
class MysqlRound extends FunctionNode
{
private $firstExpression = null;
private $secondExpression = null;
public function parse(\Doctrine\ORM\Query\Parser $parser)
{
$lexer = $parser->getLexer();
$parser->match(Lexer::T_IDENTIFIER);
$parser->match(Lexer::T_OPEN_PARENTHESIS);
$this->firstExpression = $parser->ArithmeticPrimary();
// parse second parameter if available
if(Lexer::T_COMMA === $lexer->lookahead['type']){
$parser->match(Lexer::T_COMMA);
$this->secondExpression = $parser->ArithmeticPrimary();
}
$parser->match(Lexer::T_CLOSE_PARENTHESIS);
}
public function getSql(\Doctrine\ORM\Query\SqlWalker $sqlWalker)
{
// use second parameter if parsed
if (null !== $this->secondExpression){
return 'ROUND('
. $this->firstExpression->dispatch($sqlWalker)
. ', '
. $this->secondExpression->dispatch($sqlWalker)
. ')';
}
return 'ROUND(' . $this->firstExpression->dispatch($sqlWalker) . ')';
}
}
编写了许多Doctrine2扩展here。所有归功于@beberlei的伟大作品。有许多功能可供使用(IFELSE
,IFNULL
,NULLIF
,COS
,ACOS
等...)但不是全部({{1} },ROUND
或GREATEST
丢失,但如果需要,您仍然可以自己编写。)
答案 1 :(得分:1)
我还在这里GREATEST
实施https://raw.githubusercontent.com/rodgermd/mura-show.com/master/src/Rodger/GalleryBundle/DoctrineExtension/Greatest.php(c)rodgermd @ github:
namespace Rodger\GalleryBundle\DoctrineExtension;
use Doctrine\ORM\Query\Lexer,
Doctrine\ORM\Query\AST\Functions;
class Greatest extends Functions\FunctionNode {
protected $firstExpression, $secondExpression;
public function getSql(\Doctrine\ORM\Query\SqlWalker $sqlWalker)
{
return sprintf("GREATEST(%s, %s)",
$this->firstExpression->dispatch($sqlWalker),
$this->secondExpression->dispatch($sqlWalker));
}
public function parse(\Doctrine\ORM\Query\Parser $parser)
{
$parser->match(Lexer::T_IDENTIFIER); // (2)
$parser->match(Lexer::T_OPEN_PARENTHESIS); // (3)
$this->firstExpression = $parser->ArithmeticPrimary(); // (4)
$parser->match(Lexer::T_COMMA); // (5)
$this->secondExpression = $parser->ArithmeticPrimary(); // (6)
$parser->match(Lexer::T_CLOSE_PARENTHESIS); // (3)
}
}