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

问题描述 投票:0回答:1

当我在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();
symfony symfony-2.1 symfony-2.2
1个回答
0
投票

Doctrine没有默认定义的DATE_FORMAT函数。有可能Register Custom DQL Function

但你可以很容易地比较日期(假设a.paymentDatedate类型):

$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();
© www.soinside.com 2019 - 2024. All rights reserved.