dongmeng1402 2018-01-24 11:33
浏览 35
已采纳

如何让Doctrine不创建一个永远真实的场景?

I am trying to compare datetime values using Doctrine.

I have a Doctrine query that looks like this:

$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();

... and it is creating SQL that looks like this:

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 is returning all records, including ones that are older than the datetime I specify. That makes sense in a way, since Doctrine appears to be setting up an "always true" scenario involving the timestamp comparison I want to do.

Is there a simple way to make Doctrine only return the records that are newer than my oldestAllowedDateTime value?

====

Edit: Here is the send_date content from my database.

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)
  • 写回答

1条回答 默认 最新

  • dspym82000 2018-01-24 12:42
    关注

    Your code look good, please give a try to the next function

    // 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();
    }
    

    This should do the job

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 微信小程序协议怎么写
  • ¥15 c语言怎么用printf(“\b \b”)与getch()实现黑框里写入与删除?
  • ¥20 怎么用dlib库的算法识别小麦病虫害
  • ¥15 华为ensp模拟器中S5700交换机在配置过程中老是反复重启
  • ¥15 java写代码遇到问题,求帮助
  • ¥15 uniapp uview http 如何实现统一的请求异常信息提示?
  • ¥15 有了解d3和topogram.js库的吗?有偿请教
  • ¥100 任意维数的K均值聚类
  • ¥15 stamps做sbas-insar,时序沉降图怎么画
  • ¥15 买了个传感器,根据商家发的代码和步骤使用但是代码报错了不会改,有没有人可以看看