简体   繁体   English

学说-查询日期范围

[英]Doctrine - query with date range

I wrote a query that I can call within my form to select date range and to return all database data in that range. 我编写了一个查询,可以在表单中调用该查询以选择日期范围并返回该范围内的所有数据库数据。

The api call works fine but when I set date parameters it returns an empty result. api调用工作正常,但是当我设置日期参数时,它将返回空结果。

$date = new \Datetime();

    $result = $this->getMyRepository()
        ->createQueryBuilder('a')
        ->select('a')
        ->where('a.date >= :from')
        ->andWhere('a.date <= :to')
        ->setParameter('from', $date->format('Y-m-d H:i:s'))
        ->setParameter('to',   $date->format('Y-m-d H:i:s'))
        ->orderBy('a.id')
        ->getQuery()
        ->getArrayResult();

    return $result;

It appears to me that you have used format in your from and to dates, which you don't need to. 在我看来,你已经使用formatfromto日期,你不需要。 Also, I have noticed that the same $date has been used for both from and to . 另外,我注意到fromto都使用了相同的$date I am sure you didn't mean to use like that. 我确定您不是故意那样使用。

Replace this, 取代这个

 ->setParameter('from', $date->format('Y-m-d H:i:s'))
 ->setParameter('to',   $date->format('Y-m-d H:i:s'))

with this, 有了这个,

$dateFrom = new \Datetime();
$dateFrom->setDate(2017, 1, 31);

$dateTo = new \Datetime();
$dateTo->setDate(2017, 12, 31);

->setParameter('from', $dateFrom )
->setParameter('to',   $dateTo)

Hope this helps. 希望这可以帮助。

Cheers. 干杯。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM