Laravel中实现新增商品库存与已有商品库存追加的条件逻辑
Laravel库存管理:新增/追加库存逻辑优化
你的代码逻辑方向正确,但存在关键问题:使用get()方法查询时,返回的是Collection集合对象,即使无匹配记录也会返回空集合而非null,导致if($product_check == null)的判断永远不成立,无法创建新库存记录。
以下是几种修正后的实现方案:
方案1:用exists()判断记录是否存在
public function store(StoreStockGudangRequest $request) { $validated = $request->validated(); $hasStock = StockGudang::where('product_id', $request->product_id) ->where('size_id', $request->size_id) ->where('color_id', $request->color_id) ->exists(); if (!$hasStock) { StockGudang::create($validated); } else { StockGudang::where('product_id', $request->product_id) ->where('size_id', $request->size_id) ->where('color_id', $request->color_id) ->increment('stock', $request->stock); } return redirect('/dashboard/stock')->with('success', '库存已更新!'); }
- 优势:
exists()直接返回布尔值,仅查询记录是否存在,性能更优,逻辑清晰。
方案2:用first()获取模型实例,减少重复查询
public function store(StoreStockGudangRequest $request) { $validated = $request->validated(); $stockRecord = StockGudang::where('product_id', $request->product_id) ->where('size_id', $request->size_id) ->where('color_id', $request->color_id) ->first(); if (!$stockRecord) { StockGudang::create($validated); } else { $stockRecord->increment('stock', $request->stock); } return redirect('/dashboard/stock')->with('success', '库存已更新!'); }
- 优势:仅执行一次查询获取模型实例,存在时直接调用
increment(),避免重复编写where条件,代码更简洁。
方案3:用Laravel便捷方法firstOrNew简化逻辑
public function store(StoreStockGudangRequest $request) { $validated = $request->validated(); $conditions = [ 'product_id' => $request->product_id, 'size_id' => $request->size_id, 'color_id' => $request->color_id ]; $stockRecord = StockGudang::firstOrNew($conditions); if ($stockRecord->exists) { $stockRecord->increment('stock', $request->stock); } else { $stockRecord->fill($validated)->save(); } return redirect('/dashboard/stock')->with('success', '库存已更新!'); }
- 优势:利用Laravel内置方法简化判断逻辑,代码更优雅。
注意事项
- 确保
StockGudang模型的$fillable属性包含product_id、size_id、color_id、stock字段,否则批量赋值会失败:
protected $fillable = ['product_id', 'size_id', 'color_id', 'stock'];
内容的提问来源于stack exchange,提问作者eka dita
相关产品推荐
相关产品推荐

