Symfony3 Doctrine findByDate 按月 and/or 年过滤

Symfony3 Doctrine findByDate filter by month and/or year

我需要按月 and/or 查询统计信息,但出现此错误:

Error: Expected known function, got 'YEAR'

我的代码:

public function findByMonthYear($month, $year)
{
    $qb = $this->createQueryBuilder('p')
        ->where('YEAR(p.date) = :year')
        ->andWhere('MONTH(p.date) = :month');

    $qb->setParameter('year', $year)
        ->setParameter('month', $month);

    return $qb->getQuery()->getOneOrNullResult();
}

通过一些研究表明 dql 没有 YEAR() 函数,所以它是票价...http://docs.doctrine-project.org/projects/doctrine-orm/en/latest/cookbook/working-with-datetime.html


最后,我没有坚持解决方案。所以如果你有一个干净的结果相同,我会把它作为答案。

一位同事告诉我,以下解决方案可能有效:

where('p.date = :date')
setParameter('date', ''.$year.'-'.$month.'-%') // 2016-07-%

到目前为止没有成功。

public function findByMonthYear($month, $year)
{
    $fromTime = new \DateTime($year . '-' . $month . '-01');
    $toTime = new \DateTime($fromTime->format('Y-m-d') . ' first day of next month');
    $qb = $this->createQueryBuilder('p')
        ->where('p.date >= :fromTime')
        ->andWhere('p.date < :toTime');
        ->setParameter('fromTime', $fromTime)
        ->setParameter('toTime', $toTime);
    return $qb->getQuery()->getOneOrNullResult();
}