Laravel库存超限验证功能异常,请求排查解决
Laravel库存校验功能异常修复
问题说明
需求:添加商品数量超出库存时,弹出库存不足提示。当前功能异常:添加product_id=1的商品2件时,触发错误:"error", msg: "Undefined property: stdClass::$references",预期是添加3件时才提示"商品1库存仅2件"。
现有代码
控制器代码
foreach ($request->dataTable as $dataTable) { $productId = DB::table('products') ->where('sku', $dataTable[2]) ->whereNull('deleted_at') ->select('id', 'reference') ->first(); $inventoryId = DB::table('inventories') ->where('product_id', $productId->id) ->whereNull('deleted_at') ->whereNull('sale_id') ->select('id') ->first(); if ($inventoryId == null) { return response()->json([ 'type' => 'error', 'msg' => 'No existe suficiente stock para realizar la venta del producto con referencia: ' . $productId->reference . '. Solo hay ' . $productId->references->count(), ]); } }
Product模型关联代码
public function references() { return $this->hasOne('App\Models\Inventory'); }
数据表结构
products表
| id | reference | sku |
|---|---|---|
| 1 | BCR2214 | 0108888893016580 |
| 2 | BCR2219 | 0108888893016580 |
inventories表
| ID | product_id |
|---|---|
| 1 | 1 |
| 2 | 1 |
| 3 | 2 |
错误原因分析
- 非Eloquent实例无法调用关联方法:使用
DB::table()查询返回的是stdClass对象,不是Product模型实例,因此无法访问模型中定义的references关联属性,直接导致Undefined property错误。 - 关联关系定义错误:从数据表数据来看,一个Product对应多个Inventory记录,因此应该使用
hasMany关联而非hasOne,hasOne只会返回单条关联记录,无法统计库存总数。 - 库存校验逻辑缺陷:当前代码每次循环仅查询一条可用库存记录,判断是否存在来校验库存,这种方式无法准确统计总可用库存,也无法对应用户添加的商品数量。
修复方案
步骤1:修正模型关联关系
将Product模型中的关联方法改为hasMany,同时命名为更语义化的名称:
public function inventories() { return $this->hasMany('App\Models\Inventory') ->whereNull('deleted_at') ->whereNull('sale_id'); }
步骤2:使用Eloquent查询并重构校验逻辑
修改控制器代码,先统计用户提交的每个SKU总数量,再对比对应商品的可用库存:
// 统计每个SKU的提交数量 $skuCounts = collect($request->dataTable)->countBy(function ($item) { return $item[2]; }); foreach ($skuCounts as $sku => $requestedQuantity) { // 使用Eloquent模型查询商品 $product = \App\Models\Product::where('sku', $sku) ->whereNull('deleted_at') ->first(); if (!$product) { return response()->json([ 'type' => 'error', 'msg' => '商品不存在' ]); } // 获取可用库存总数 $availableStock = $product->inventories->count(); if ($requestedQuantity > $availableStock) { return response()->json([ 'type' => 'error', 'msg' => '商品参考码: ' . $product->reference . ' 库存不足,当前仅存 ' . $availableStock . ' 件' ]); } }
补充说明
- 重构后的逻辑先聚合用户提交的商品数量,再一次性对比库存,避免循环内重复查询,逻辑更高效准确。
- 关联方法中预设可用库存的过滤条件,简化后续业务代码调用。
内容的提问来源于stack exchange,提问作者user20389386
相关产品推荐
相关产品推荐

