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

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表

idreferencesku
1BCR22140108888893016580
2BCR22190108888893016580

inventories表

IDproduct_id
11
21
32

错误原因分析

  1. 非Eloquent实例无法调用关联方法:使用DB::table()查询返回的是stdClass对象,不是Product模型实例,因此无法访问模型中定义的references关联属性,直接导致Undefined property错误。
  2. 关联关系定义错误:从数据表数据来看,一个Product对应多个Inventory记录,因此应该使用hasMany关联而非hasOne,hasOne只会返回单条关联记录,无法统计库存总数。
  3. 库存校验逻辑缺陷:当前代码每次循环仅查询一条可用库存记录,判断是否存在来校验库存,这种方式无法准确统计总可用库存,也无法对应用户添加的商品数量。

修复方案

步骤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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.04 14:05:17