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

Laravel中无法使用数组更新库存表问题求助

问题分析与解决方案

核心问题点

  1. 循环对象错误:你把$data作为循环目标,但$data是仅包含items键的数组,实际要遍历的是$data['items']这个查询结果集合。
  2. 数组取值逻辑错误:循环内的$product_item['items']['id']和$product_item['quantity']['new_quantity']完全不符查询结果结构——new_quantity是查询返回的直接字段,id是inventory_items的原生字段,直接通过$product_item['id']和$product_item['new_quantity']取值即可。
  3. 查询构造器字段覆盖问题:同时使用select()和selectRaw()会导致前者被覆盖,应该用addSelect()追加自定义计算字段。
  4. 批量赋值限制:如果InventoryItem模型未将quantity加入$fillable属性,Laravel会拦截批量赋值操作。

修改后的代码

// 修正查询逻辑,用addSelect追加计算字段
$data['items'] = DB::table('inventory_items')
    ->join('sorder_parts', 'inventory_items.id', '=', 'sorder_parts.inventory_id')
    ->where('sorder_parts.sorder_id', $id)
    ->select('inventory_items.*')
    ->addSelect(DB::raw('inventory_items.quantity - sorder_parts.quantity AS new_quantity'))
    ->get()
    ->toArray();

// 遍历正确的items集合
foreach ($data['items'] as $product_item) {
    InventoryItem::updateOrCreate(
        ['id' => $product_item['id']],
        ['quantity' => $product_item['new_quantity']]
    );
}

额外优化建议

  • 添加事务保障:库存更新属于敏感操作,用事务避免部分更新失败:
DB::beginTransaction();
try {
    foreach ($data['items'] as $product_item) {
        InventoryItem::updateOrCreate(
            ['id' => $product_item['id']],
            ['quantity' => $product_item['new_quantity']]
        );
    }
    DB::commit();
} catch (\Exception $e) {
    DB::rollBack();
    // 可在此记录错误日志或抛出异常
    throw $e;
}
  • 检查模型批量赋值配置:在InventoryItem模型中确保存在:
protected $fillable = ['quantity', 'id']; // 按需添加其他需要批量赋值的字段
  • 性能优化:如果数据量较大,可改用批量更新语句减少数据库交互次数。

内容的提问来源于stack exchange,提问作者surviver lartey

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.12 07:15:01