You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何筛选日期为今日的实体?多种查询方案均失效求助

筛选今日Doctrine实体的正确方法

以下是你尝试过的无效方法及问题分析,附正确实现方案:

无效尝试与问题点

方式一:字符串日期直接匹配

$time = date('Y/m/d');
$alerts = $repository->findBy(['datum' => $time]);

问题:若datum是Doctrine的DateTime类型,字符串与日期对象类型不匹配,无法命中记录;若字段带时间戳,纯日期字符串也匹配不到带时间的条目。

方式二:错误的LIKE参数引用

$time = date('Y/m/d');
$lessons = $repository->createQueryBuilder('q')
    ->where('q.datum LIKE currentDate')
    ->setParameter('currentDate', $time);

问题:参数必须用:currentDate格式引用;LIKE是字符串模糊匹配,不适用于日期查询;且未调用getQuery()->getResult()执行查询,dd($lessons)输出的是查询构建器对象而非结果集。

方式三:未执行查询的范围条件

$today = new \DateTime('today');
$tomorrow = new \DateTime('today +1 day');

$lessons = $repository->createQueryBuilder('q')
    ->where('q.datum > :today')
    ->andWhere('q.datum < :tomorrow')
    ->setParameter('today', $today)
    ->setParameter('tomorrow', $tomorrow);

问题:缺少getQuery()->getResult()执行查询;q.datum > :today会漏掉当天0点整的记录,应改为>=。

正确实现方案

方案一:用Doctrine日期函数提取日期(推荐)

直接提取日期部分匹配,无需处理时间范围:

$today = new \DateTime('today');

$lessons = $repository->createQueryBuilder('q')
    ->where('DATE(q.datum) = :today')
    ->setParameter('today', $today->format('Y-m-d'))
    ->getQuery()
    ->getResult();

注:需确保Doctrine支持DATE()函数,若不支持可在ORM配置中启用Doctrine\ORM\Query\AST\Functions\DateFunction。

方案二:精确时间范围查询

保留时间精度的范围匹配,修正条件并执行查询:

$today = new \DateTime('midnight');
$tomorrow = (new \DateTime('midnight'))->modify('+1 day');

$lessons = $repository->createQueryBuilder('q')
    ->where('q.datum >= :today')
    ->andWhere('q.datum < :tomorrow')
    ->setParameter('today', $today)
    ->setParameter('tomorrow', $tomorrow)
    ->getQuery()
    ->getResult();

>= :today包含当天0点的记录,< :tomorrow排除次日0点及以后的条目,确保所有今日记录都被匹配。

方案三:针对字符串类型日期字段

若datum是数据库字符串类型(不建议,推荐用DateTime类型),需确保格式完全一致:

$today = date('Y/m/d'); // 与数据库存储格式完全相同
$alerts = $repository->findBy(['datum' => $today]);

内容的提问来源于stack exchange,提问作者Gleyveon

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.22 16:05:25