我正在尝试使用 Doctrine 比较日期时间值。
我有一个如下所示的 Doctrine 查询:
$interval = new \DateInterval('PT'. 2 .'H');
$oldestAllowedDateTime = new \DateTime();
$oldestAllowedDateTime = $oldestAllowedDateTime->sub( $interval );
$queryBuilder = $repository->createQueryBuilder('pn');
$queryBuilder = $queryBuilder->select('notification')
->from('AppBundle\Entity\PushNotification','notification')
->where('pn.isSent IS NULL OR pn.isSent = 0')
->andwhere('pn.sendDate > :oldestAllowedDateTime')
->orderBy('pn.sendDate', 'DESC')
;
$queryBuilder->setParameter('oldestAllowedDateTime',$oldestAllowedDateTime);
$result = $queryBuilder->getQuery()->getResult();
...它正在创建如下所示的 SQL:
SELECT p0_.id AS id_0,
p0_.content AS content_1, p0_.last_offset AS last_offset_2,
p0_.failure_count AS failure_count_3, p0_.is_sent AS is_sent_4,
p0_.send_date AS send_date_5 FROM push_notification p1_,
push_notification p0_ WHERE (p1_.is_sent IS NULL OR p1_.is_sent = 0)
AND p1_.send_date > ? ORDER BY p1_.send_date DESC
Doctrine 正在返回所有记录,包括早于我指定的日期时间的记录。这在某种程度上是有道理的,因为 Doctrine 似乎正在建立一个“始终正确”的场景,涉及我想要进行的时间戳比较。
有没有一种简单的方法可以让 Doctrine 只返回比我的oldestAllowedDateTime 值更新的记录?
====
编辑:这是我的数据库中的 send_date 内容。
mysql> SELECT send_date FROM push_notification;
+---------------------+
| send_date |
+---------------------+
| 2018-01-24 05:51:21 |
| 2018-01-24 11:44:30 |
+---------------------+
2 rows in set (0.00 sec)
最佳答案
您的代码看起来不错,请尝试下一个功能
// Inside your PushNotificationrRepository
public function getNotSentByDateInterval(\DateTimeInterval $interval)
{
$from = (new \DateTime())->sub($interval);
$qb = $this->createQueryBuilder('pn');
$qb->where('pn.isSent IS NULL OR pn.isSent = 0')
->andWhere('pn.sendDate > :oldestAllowedDateTime')
->setParameter('oldestAllowedDateTime', $from)
->orderBy('pn.sendDate', 'DESC')
;
return $qb->getQuery()->getResult();
}
这应该可以完成工作
关于php - 如何让 Doctrine 不创造一个永远真实的场景?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48421494/