Retrieve items by month and year with Symfony and Doctrine
Putting something like this in your Repository should get you started. I haven't tested it aside from the 'last day of this month'
bit which seems to work fine.
/** * @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();}
This appears to be working, although I will definitely need to modify the way I construct the dates (and move the function into the repo). I had originally forgotten the '.date' bit of DQL, and there was no need to output the DateTime object as a format.
// 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.date BETWEEN :start AND :end')->setParameter('start', $startDate)->setParameter('end', $endDate)->getQuery()->getResult();// $notes = $this->em->getRepository('MrshllSiteBundle:Note')->findByDate();return $notes;