Mrs*_*001 3 php select doctrine date symfony
我需要使用 Doctrine 检索特定类型的所有项目,其中“日期”字段存储为日期时间。这意味着我也在使用 PHP DateTime 对象。
我需要做两件事:如果给定月份和年份,检索该月份和年份的所有记录;如果没有给出月份和年份,则检索该月的所有记录。
我一直在研究在 Doctrine Query Builder 中使用 BETWEEN 语句,但无法弄清楚如何从“现在”创建的 PHP DateTime 对象中干净地提取月份和年份,以便 DateTime 的时间部分不会影响查询. 我也看不到将 DateTime 中日期的日部分设置为 01 而不影响月份和年份的方法。
我认为这将是一项相当标准的任务,但找不到解决方案。任何帮助表示赞赏。
编辑:
找到了一种获取两者之间日期的方法,但 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;
}
Run Code Online (Sandbox Code Playgroud)
把这样的东西放在你的存储库中应该会让你开始。除了'last day of this month'似乎工作正常的位之外,我还没有对其进行测试。
/**
* @param int $month
* @param int $year
*
* @return object[]
*/
public function findByDate($year = null, $month = null)
{
if ($month === null) {
$month = (int) date('m');
}
if ($year === null) {
$year = (int) date('Y');
}
$startDate = new \DateTimeImmutable("$year-$month-01T00:00:00");
$endDate = $startDate->modify('last day of this month')->setTime(23, 59, 59);
$qb = $this->createQueryBuilder('object');
$qb->where('object.date BETWEEN :start AND :end');
$qb->setParameter('start', $startDate->format('??Y-m-d H:i:s'));
$qb->setParameter('end', $endDate->format('??Y-m-d H:i:s'));
return $qb->getQuery()->getResult();
}
Run Code Online (Sandbox Code Playgroud)