如何在Doctrine 2 DQL中使用DATE()?

时间:2014-09-17 06:21:57

标签: php mysql symfony doctrine-orm doctrine

在Symfony中,当我在mysql中使用以下带有DATE函数的查询时出现错误

    SELECT employer.companyName AS employerName, jobs.jobId, jobs.industryId, 
jobs.focusId, jobs.companyName, jobs.employerId, jobs.jobTitle, DATE(jobs.createdDate) AS 
createdDate , DATE(jobs.endDate) AS endDate , jobs.replyTo, jobs.featured , jobs.jobType, 
jobs.status  FROM Acme\\AppsBundle\\Entity\\Jobs jobs , Acme\\AppsBundle\\Entity\\Employer 
employer  WHERE  jobs.employerId = employer.employerId  GROUP BY  jobs.jobId  ORDER BY 
jobs.jobId DESC 

为什么这个和什么样的解决方法可以克服这种情况,在数据库中这些字段,即end_date存储为mysql类型'date'

    [2014-09-17 05:52:42] request.CRITICAL: Uncaught PHP Exception Doctrine\ORM\Query
\QueryException: "[Syntax Error] line 0, col 138: Error: Expected known function, got 
'DATE'" at /.../Doctrine/ORM/Query/QueryException.php line 52 {"exception":"[object] 
(Doctrine\\ORM\\Query\\QueryException: [Syntax Error] line 0, col 138: Error: Expected known function, got 'DATE' at /var/w.../doctrine/orm/lib/Doctrine/ORM/Query
/QueryException.php:52, Doctrine\\ORM\\Query\\QueryException: SELECT employer.companyName 
AS employerName, jobs.jobId, jobs.industryId, jobs.focusId, jobs.companyName, jobs.employerId, jobs.jobTitle, DATE(jobs.createdDate) AS createdDate , DATE(jobs.endDate) 
AS endDate , jobs.replyTo, jobs.featured , jobs.jobType, jobs.status  FROM Acme\\AppsBundle
\\Entity\\Jobs jobs , Acme\\AppsBundle\\Entity\\Employer employer  WHERE  jobs.employerId 
= employer.employerId  GROUP BY  jobs.jobId  ORDER BY  jobs.jobId DESC  at /var/w...
/doctrine/orm/lib/Doctrine/ORM/Query/QueryException.php:41)"} []

3 个答案:

答案 0 :(得分:11)

除了已接受的答案外,https://github.com/beberlei/DoctrineExtensions还提供了大量预先构建的自定义功能。

然后可以在您的配置中注册这些内容,如

doctrine:
    orm:
        dql:
            string_functions:
                DATE: DoctrineExtensions\Query\Mysql\Date

然后可以在您的DQL中使用(如在您的查询中),如

DATE(jobs.endDate) AS endDate

答案 1 :(得分:8)

DQL只知道几个标准的sql函数(例如coalesce)。为了能够使用您的自定义函数,您需要注册它并告诉doctrine如何将其转换为原始sql。请遵循以下指南:

Symfony Doc

Doctrine Doc

并查看我的回答here

答案 2 :(得分:2)

或者,如果您不想添加新依赖项,则可以使用以下代码:

$dateTime = new \DateTime();
$qb
   ->andWhere('jobs.endDate BETWEEN :dateMin AND :dateMax')
   ->setParameters(
       [
            'dateMin' => $dateTime->format('Y-m-d 00:00:00'),
            'dateMax' => $dateTime->format('Y-m-d 23:59:59'),
       ]
    );