在symfony2中的where子句中使用日期格式进行查询

时间:2013-03-18 17:36:30

标签: symfony symfony-2.1 symfony-2.2

当我在where子句中运行带日期的查询时,显示以下错误...

[Syntax Error] line 0, col 129: Error: Expected known function, got 'DATE_FORMAT'

查询如下:

$query = $this->getEntityManager()->createQuery(
  "SELECT a.id, a.amont, a.paymentDescrip, a.paymentType, a.paymentDate
   FROM RegalSmsBundle:DailyTransaction a 
   WHERE DATE_FORMAT(a.paymentDate,'%Y-%m-%d') = :paymentDate
        and a.students = :studentId" 

    )->setParameter('studentId', $studentId)
    ->setParameter('paymentDate','2013-03-11');


 return $query->getResult();

1 个答案:

答案 0 :(得分:0)

默认情况下,Doctrine没有定义DATE_FORMAT函数。可以Register Custom DQL Function

但您可以轻松比较日期(假设a.paymentDate属于date类型):

$query = $this->getEntityManager()->createQuery("
        SELECT a.id, a.amont, a.paymentDescrip, a.paymentType, a.paymentDate
        FROM RegalSmsBundle:DailyTransaction a 
        WHERE a.paymentDate = :paymentDate AND a.students = :studentId
    ")
    ->setParameter('studentId', $studentId)
    ->setParameter('paymentDate', new \DateTime('2013-03-11'))
;

return $query->getResult();

编辑:我更喜欢使用querybuider编写DQL。它看起来像这样:

$qb = $this->getEntityManager()->getRepository('RegalSmsBundle:DailyTransaction')->createQueryBuilder('a');
$qb
    ->select('a') // select whole entity
    ->where($qb->expr()->andX(
        $qb->expr()->eq('a.paymentDate', ':paymentDate')
        $qb->expr()->eq('a.students', ':studentId')
    ))
    ->setParameter('studentId', $studentId)
    ->setParameter('paymentDate', new \DateTime('2013-03-11'))
;

return $qb->getQuery()->getResult();