问题
I have written a custom function for the DQL:
<?php namespace Bundle\DQL\Functions;
use Doctrine\ORM\Query\AST\Functions\FunctionNode;
use Doctrine\ORM\Query\Lexer;
use Doctrine\ORM\Query\SqlWalker;
use Doctrine\ORM\Query\Parser;
/**
* "DATE_COMPARE" "(" ArithmeticPrimary "," ComparisonOperator "," ArithmeticPrimary ")"
*/
class DateCompareFunction extends FunctionNode
{
public $date1;
public $date2;
public $operator;
/**
* @override
* @param SqlWalker $sqlWalker
* @return string
* @throws \Doctrine\DBAL\DBALException
*/
public function getSql(SqlWalker $sqlWalker)
{
return sprintf(
'TRUNC(%s) %s TRUNC(%s)',
$this->date1->dispatch($sqlWalker),
$this->operator,
$this->date2->dispatch($sqlWalker)
);
}
/**
* @override
* @param Parser $parser
*/
public function parse(Parser $parser)
{
$parser->match(Lexer::T_IDENTIFIER);
$parser->match(Lexer::T_OPEN_PARENTHESIS);
$this->date1 = $parser->ArithmeticPrimary();
$parser->match(Lexer::T_COMMA);
$this->operator = $parser->ComparisonOperator();
$parser->match(Lexer::T_COMMA);
$this->date2 = $parser->ArithmeticPrimary();
$parser->match(Lexer::T_CLOSE_PARENTHESIS);
}
}
And my where stmt looks like this:
$query = $em->createQueryBuilder()
->select('evt')
->from('Application\Model\Event', 'evt')
->where('evt.USR_ID in (:uid)')
->setParameter('uid', $usersId);
if (null !== $from) {
$query->andWhere('DATE_COMPARE(evt.DAY, >, TO_DATE(:from, \'yyyy-mm-dd\'))')
->setParameter('from', $from);
The problem is that Doctrine raise an exception for having a WHERE
statement without comparison symbol:
object(Doctrine\ORM\Query\QueryException)[347]
protected 'message' => string '[Syntax Error] line 0, col 130: Error: Expected =, <, <=, <>, >, >=, !=, got ')'' (length=80)
private 'string' (Exception) => string '' (length=0)
protected 'code' => int 0
protected 'file' => string 'C:\Workspace\app\hcalendar\vendor\doctrine\orm\lib\Doctrine\ORM\Query\QueryException.php' (length=88)
protected 'line' => int 52
private 'trace' (Exception) =>
I have tried adding a stmt = TRUE
, but the generated statement isn't understood by oracle, hwo can I do a where statement without any comparison symbol ? (just a true/false function return)
回答1:
Why do you need this function? you can do the where condition without custom function, just write:
$query->andWhere('evt.day > :from')->setParameter('from', $from);
where the variable $from
should be a DateTime object, and if you want the Oracle TRUNC
function you can implement it by it self as in here https://github.com/ZeinEddin/ZeDoctrineExtensions/blob/master/lib/ZeDoctrineExtensions/Query/Oracle/TruncDate.php and just use it like this:
$query->andWhere('trunc(evt.day) > :from')->setParameter('from', $from);
If you want you can install this module for a ZF2 project and you will have the TruncDate
function ready to be used in your project
来源:https://stackoverflow.com/questions/26275812/doctrine-2-where-condition-without-comparison