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

Laravel的select查询中获取当前时间返回null怎么解决

原有代码问题说明

  1. DB::raw('date(\'d-m-y\') as dateCurrent' )写法错误:SQL的DATE()函数作用是提取合法日期值的日期部分,传入的'd-m-y'是格式字符串而非有效日期参数,因此返回null。
  2. whereDate('status', 3)写法错误:whereDate方法仅用于日期类型字段的日期匹配,若status为整型状态字段,应直接使用where('status', 3)。

可行实现方案

方案1:使用数据库侧当前日期(推荐,避免PHP和数据库服务器时区不一致问题)

如果需要d-m-y格式的自定义日期:

$product = Product::select('id', 'name', 'status', DB::raw("DATE_FORMAT(CURDATE(), '%d-%m-%y') as dateCurrent"))
    ->where('status', 3)
    ->get()
    ->toArray();

如果不需要自定义格式,直接返回标准YYYY-MM-DD格式日期,可简化为:

$product = Product::select('id', 'name', 'status', DB::raw('CURDATE() as dateCurrent'))
    ->where('status', 3)
    ->get()
    ->toArray();

方案2:使用PHP侧当前日期

如果需要统一使用PHP服务端的时间,可直接注入PHP生成的日期值:

$currentDate = date('d-m-y');
$product = Product::select('id', 'name', 'status', DB::raw("'{$currentDate}' as dateCurrent"))
    ->where('status', 3)
    ->get()
    ->toArray();

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.04 07:54:02