【问题标题】:Compare dates between datetimes with Doctrine使用 Doctrine 比较日期时间之间的日期
【发布时间】:2023-04-06 06:12:01
【问题描述】:
我有一个带有日期字段的表格的 Syfmony2 应用程序。此日期字段是 DateTime 类型。
我需要获取与现在相同日期的所有实体。
但如果我这样做:
$now = new \DateTime();
$data = $entityRepository->findByDate($now);
我得到 0 个结果,因为 Doctrine 正在比较 DateTime 对象,而我只需要比较年、月和日,而不是小时……只比较日期对象,而不是 DateTime。
有什么想法吗?
谢谢:D
【问题讨论】:
标签:
php
symfony
datetime
doctrine-orm
doctrine
【解决方案1】:
存储库中的方法
public function getDays(\DateTime $firstDateTime, \DateTime $lastDateTime)
{
$qb = $this->getEntityManager()->createQueryBuilder()
->select('c')
->from('ProjectBundle:Calendar', 'c')
->where('c.date BETWEEN :firstDate AND :lastDate')
->setParameter('firstDate', $firstDateTime)
->setParameter('lastDate', $lastDateTime)
;
$result = $qb->getQuery()->getResult();
return $result;
}
和行动
public function calendarAction()
{
$currentMonthDateTime = new \DateTime();
$firstDateTime = $currentMonthDateTime->modify('first day of this month');
$currentMonthDateTime = new \DateTime();
$lastDateTime = $currentMonthDateTime->modify('last day of this month');
$days = $this->getDoctrine()
->getRepository('ProjectBundle:Calendar')
->getDays($firstDateTime, $lastDateTime);
return ['days' => $days];
}
【解决方案2】:
我看到这个简单的方法:
$now = new \DateTime();
$data = $entityRepository->getByDate($now);
然后在您的存储库中
public function getByDate(\Datetime $date)
{
$from = new \DateTime($date->format("Y-m-d")." 00:00:00");
$to = new \DateTime($date->format("Y-m-d")." 23:59:59");
$qb = $this->createQueryBuilder("e");
$qb
->andWhere('e.date BETWEEN :from AND :to')
->setParameter('from', $from )
->setParameter('to', $to)
;
$result = $qb->getQuery()->getResult();
return $result;
}
【解决方案3】:
原则中的date 和datetime 类型之间存在差异。
date:将 SQL DATETIME 映射到 PHP DateTime 对象的类型。
datetime:将 SQL DATETIME/TIMESTAMP 映射到 PHP DateTime 的类型
对象。
确保您已将列类型设置为 date 而不是 datetime。
或者 - 作为一种解决方法 - 您可以从原始 date1 获取日期,然后使用自定义存储库在同一天 date2 -> 00:00:00 和同一天 date3 -> 23:59:59 之间进行搜索方法。