Laravel 8中如何存储过期产品 控制器代码相关问题咨询
Laravel 8 过期产品功能代码修正方案
现有代码问题
whereNotNull方法仅可用于校验字段非空,无法同时传入比较运算符、时间参数完成过期时间判断,不符合Laravel查询构造器语法规则- 原有代码仅查询了
expiry_date单个字段,未实现过期产品的存储逻辑
仅查询过期产品的修正代码
如果仅需要查询返回所有已过期的产品数据,调整后代码如下:
public function index() { $expiredProducts = Product::whereNotNull('expiry_date') ->where('expiry_date', '<', now()) ->get(); return $expiredProducts; }
实现过期产品存储归档的完整代码
如果你需要把过期产品写入专门的归档表存储,提前创建好expired_products表、对应模型ExpiredProduct后,代码调整如下:
public function index() { // 查询所有已过期产品 $expiredProducts = Product::whereNotNull('expiry_date') ->where('expiry_date', '<', now()) ->get(); // 批量写入过期产品归档表 ExpiredProduct::insert($expiredProducts->toArray()); // 可选:如果需要删除原产品表的过期数据,取消注释下行即可 // Product::whereIn('id', $expiredProducts->pluck('id'))->delete(); return response()->json([ 'code' => 200, 'message' => '过期产品存储完成', 'data' => $expiredProducts ]); }
注意事项
- 请确保
Product、ExpiredProduct模型的$fillable属性已经配置好所有需要批量写入的字段,避免触发批量赋值报错 - 请检查
config/app.php中的timezone时区配置和业务使用的时区一致,避免时间判断出现偏差 - 如果过期产品数据量较大,建议使用
chunk方法分块处理,避免内存溢出:
Product::whereNotNull('expiry_date') ->where('expiry_date', '<', now()) ->chunk(100, function ($products) { ExpiredProduct::insert($products->toArray()); // 可选删除原数据 // Product::whereIn('id', $products->pluck('id'))->delete(); });
内容的提问来源于stack exchange,提问作者th tom
相关产品推荐
相关产品推荐

