Laravel的select查询中获取当前时间返回null怎么解决
原有代码问题说明
DB::raw('date(\'d-m-y\') as dateCurrent' )写法错误:SQL的DATE()函数作用是提取合法日期值的日期部分,传入的'd-m-y'是格式字符串而非有效日期参数,因此返回null。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
相关产品推荐
相关产品推荐

