【发布时间】:2016-12-22 18:52:01
【问题描述】:
我需要使用 Doctrine 检索特定类型的所有项目,其中“日期”字段存储为 DateTime。这意味着我也在使用 PHP DateTime 对象。
我需要做两件事:如果给定月份和年份,则检索该月份和年份的所有记录;如果没有给出月份和年份,则检索本月的所有记录。
我一直在研究在 Doctrine Query Builder 中使用 BETWEEN 语句,但无法弄清楚如何从“现在”创建的 PHP DateTime 对象中干净地提取月份和年份,这样 DateTime 的时间部分就不会影响查询。我也看不到将 DateTime 中日期的日期部分设置为 01 而不影响月份和年份的方法。
我认为这将是一项相当标准的任务,但找不到解决方案。任何帮助表示赞赏。
编辑:
找到了一种获取两者之间日期的 hacky 方法,但 Doctrine 返回一个空数组。使用以下代码
/**
* Returns feed for month and year
*/
public function getMonthYearFeed($month, $year)
{
// Create two times at the start of this month and next month
$startDate = \DateTime::createFromFormat('d-n-Y', "01-".$month."-".$year);
$startDate->setTime(0, 0 ,0);
$endDate = \DateTime::createFromFormat('d-n-Y', "01-".($month+1)."-".$year);
$endDate->setTime(0, 0, 0);
$notes = $this->em->getRepository('AppBundle:Note')->createQueryBuilder('n')->where('n BETWEEN :start AND :end')->setParameter('start', $startDate->format('Y-m-d H:i:s'))->setParameter('end', $endDate->format('Y-m-d H:i:s'))->getQuery()->getResult();
return $notes;
}
【问题讨论】:
-
提供代码以显示您尝试过的内容。
标签: php symfony date select doctrine