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
相关产品推荐
相关产品推荐

