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

Laravel 5.4使用时间戳查询无数据返回问题排查

问题分析与解决

核心错误:查询逻辑矛盾

你的查询条件where('time_from', '>=', $current_date)->where('time_to', '<', $current_date)完全不符合正常的时间范围逻辑——它要求time_from大于等于当前时间,同时time_to小于当前时间,这意味着time_from > time_to,但正常的预订记录必然是time_from <= time_to,所以这个条件永远匹配不到任何数据。

正确查询写法(按需求选择)

1. 查询当前正在进行的预订(当前时间在time_from和time_to之间)

// 直接用time()获取当前时间戳,比strtotime(date(...))更高效简洁
$current_timestamp = time();
        
$bookings = MachineBooking::with('userDetail')
    ->where('machine_id', $machine_id)
    ->where('time_from', '<=', $current_timestamp)
    ->where('time_to', '>', $current_timestamp)
    ->get();

2. 查询未来尚未开始的预订

$current_timestamp = time();
        
$bookings = MachineBooking::with('userDetail')
    ->where('machine_id', $machine_id)
    ->where('time_from', '>', $current_timestamp)
    ->get();

3. 查询已结束的历史预订

$current_timestamp = time();
        
$bookings = MachineBooking::with('userDetail')
    ->where('machine_id', $machine_id)
    ->where('time_to', '<=', $current_timestamp)
    ->get();

额外优化建议

推荐使用Laravel自带的Carbon类处理时间,可读性更强且不易出错:

use Carbon\Carbon;

$current_time = Carbon::now();
$bookings = MachineBooking::with('userDetail')
    ->where('machine_id', $machine_id)
    ->where('time_from', '<=', $current_time->timestamp)
    ->where('time_to', '>', $current_time->timestamp)
    ->get();

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.07 06:05:14