【问题标题】:Symfony3 Doctrine findByDate filter by month and/or yearSymfony3 Doctrine findByDate 按月和/或年过滤
【发布时间】:2016-07-13 08:24:29
【问题描述】:

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

错误:预期的已知函数,得到 '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-%

目前没有成功。

【问题讨论】:

标签: datetime doctrine-orm symfony dql


【解决方案1】:
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();
}

【讨论】:

    猜你喜欢
    • 2014-02-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-03-08
    • 1970-01-01
    • 1970-01-01
    • 2017-12-13
    • 1970-01-01
    相关资源
    最近更新 更多