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

Laravel Eloquent查询:筛选timestamp字段时间为09:00的数据

在Laravel Eloquent查询中添加planned_completion_date时间为09:00的筛选条件

方法一:使用Laravel内置的whereTime方法

Laravel提供了whereTime便捷方法,可直接匹配时间字段的时分部分,无需编写原生SQL,且跨数据库兼容:

$portings = Porting::with('items')
    ->where('status', AbstractPorting::STATUS_ACCEPTED)
    ->where(function ($q) {
        $q->where('planned_completion_date', '<=', now()) // 用now()替代date()更简洁且符合Laravel规范
          ->orWhereColumn('planned_completion_date', '<', 'first_possible_date');
    })
    ->whereTime('planned_completion_date', '09:00') // 筛选时间为09:00的记录
    ->get();

方法二:使用原生SQL函数(针对特定数据库)

如果需要更精细的控制,比如针对MySQL数据库,可以用TIME()函数提取时间部分进行匹配:

use Illuminate\Support\Facades\DB;

$portings = Porting::with('items')
    ->where('status', AbstractPorting::STATUS_ACCEPTED)
    ->where(function ($q) {
        $q->where('planned_completion_date', '<=', now())
          ->orWhereColumn('planned_completion_date', '<', 'first_possible_date');
    })
    ->whereRaw('TIME(planned_completion_date) = ?', ['09:00:00'])
    ->get();

可选逻辑调整(仅在or分支添加时间筛选)

如果你的需求是仅在orWhereColumn的分支下添加时间筛选(即「planned_completion_date小于等于当前时间 或(planned_completion_date小于first_possible_date且时间为09:00)」),则需要调整闭包内的条件结构:

$portings = Porting::with('items')
    ->where('status', AbstractPorting::STATUS_ACCEPTED)
    ->where(function ($q) {
        $q->where('planned_completion_date', '<=', now())
          ->orWhere(function ($subQ) {
              $subQ->whereColumn('planned_completion_date', '<', 'first_possible_date')
                   ->whereTime('planned_completion_date', '09:00');
          });
    })
    ->get();

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.17 13:45:31