我正在尝试实现自定义功能以在两个字段上获得时间差,但是我一直遇到错误...我已经阅读了类似的错误,但是答案并没有真正帮助。
我一直在这样做:
<?php
namespace BundleDQL;
use DoctrineORMQueryLexer;
use DoctrineORMQueryASTFunctionsFunctionNode;
/**
* Custom DQL function returning the difference between two DateTime values
*
* usage TIME_DIFF(dateTime1, dateTime2)
*/
class TimeDiffFunction extends FunctionNode
{
/**
* @var string
*/
public $dateTime1;
/**
* @var string
*/
public $dateTime2;
public function parse(DoctrineORMQueryParser $parser)
{
$parser->match(Lexer::T_IDENTIFIER);
$parser->match(Lexer::T_OPEN_PARENTHESIS);
$this->dateTime1 = $parser->ArithmeticPrimary();
$parser->match(Lexer::T_COMMA);
$this->dateTime2 = $parser->ArithmeticPrimary();
$parser->match(Lexer::T_CLOSE_PARENTHESIS);
}
public function getSql(DoctrineORMQuerySqlWalker $sqlWalker)
{
return 'TIME_TO_SEC(TIMEDIFF(' .
$this->dateTime1->dispatch($sqlWalker) . ', ' .
$this->dateTime2->dispatch($sqlWalker) .
'))';
}
}
config.yml
orm:
auto_generate_proxy_classes: %kernel.debug%
auto_mapping: true
dql:
numeric_functions:
time_diff: Bundle:DQL:TimeDiffFunction
控制器:
$em = $this->getDoctrine()->getManager();
$detail1 = $em->getRepository('Bundle:Detail')->find(96);
//$detail2 = $em->getRepository('Bundle:Detail')->find(138);
$query = $em->createQuery("SELECT time_diff(eng.updatedDate, eng.updatedDate) FROM BundleEntityDetail eng WHERE eng.id = :id1");
$query->setParameter('id1', $detail1->getId());
$entities = $query->getResult();
die(var_dump($entities));
这样做:
FatalErrorException: Error: Class 'Bundle:DQL:TimeDiffFunction' not found in C:xampphtdocsEngMgmtvendordoctrineormlibDoctrineORMQueryParser.php line 3070
但是在控制器上这样做
$query = $em->createQuery("SELECT BundleDQLTimeDiff(eng.updatedDate, eng.updatedDate) FROM BundleEntityDetail eng WHERE eng.id = :id1");
我得到:
[Syntax Error] line 0, col 7: Error: Expected known function, got 'BundleDQLTimeDiff'
,如果我在控制器上这样做:
$query = $em->createQuery("SELECT BundleDQLtime_diff(eng.updatedDate, eng.updatedDate) BundleEntityDetail eng WHERE eng.id = :id1");
我得到:
[Syntax Error] line 0, col 47: Error: Expected DoctrineORMQueryLexer::T_FROM, got '('
那么,问题是,我该如何使其起作用?我真的需要它。
遵循以下示例:
http://symfony.com/doc/current/cookbook/doctrine/custom_dql_functions.html
http://docs.doctrine-project.org/projects/doctrine-orm/en/latest/cookbook/dql-user-defined-functions.html
使用完全合格的类名
dql:
numeric_functions:
time_diff: BundleDQLTimeDiffFunction
捆绑包是捆绑包的一个奇怪名称。您确定这是正确的吗?
选择time_diff(eng.updateddate,eng.updateddate)...一旦正确安装了它。