
本文介绍一种安全、可控的库存扣减方案:当用户下单数量超过单条库存记录余量时,自动按顺序(如订单创建时间)遍历多条同商品库存记录,逐条扣减直至满足需求,避免超卖或负库存。
在电商或酒类仓储系统中,同一商品(如 id_wine = 1)可能因分属不同采购批次或客户订单,分散存储于多条库存记录中(每条对应唯一 id_order)。此时若用户一次性下单 5 瓶,而数据库中存在两条记录:qty=4(id=1)和 qty=1(id=2),理想行为应是先扣减第一条 4 瓶,再扣减第二条 1 瓶,而非仅操作首条导致余量变为 -1——这正是原子性与业务逻辑一致性的关键所在。
Laravel 原生的 decrement() 方法仅作用于单条模型,无法智能分配扣减量。因此,需采用「查询 + 循环 + 条件扣减」策略,确保过程可预测、可验证、可中断。以下是推荐实现:
✅ 正确做法:分步扣减 + 余量追踪
$requestedQty = (int) $request->quantita;
$wineId = $wine_id;
$restaurantId = Auth::user()->id_restaurant;
// 1. 查询所有可用库存(按 id_order 升序,保证处理顺序)
$stocks = Warehouse::where('id_restaurant', $restaurantId)
->where('id_wine', $wineId)
->where('quantita_restante', '>', 0)
->orderBy('id_order') // 或用 created_at 等业务排序字段
->get();
if ($stocks->isEmpty()) {
throw new \Exception('商品库存不足');
}
// 2. 逐条扣减,动态更新剩余需扣数量
foreach ($stocks as $stock) {
if ($requestedQty <= 0) break; // 扣减完成,提前退出
$available = (int) $stock->quantita_restante;
$toDeduct = min($available, $requestedQty);
// 使用事务保障原子性(强烈建议)
DB::transaction(function () use ($stock, $toDeduct) {
$stock->decrement('quantita_restante', $toDeduct);
// 可选:记录扣减日志
InventoryLog::create([
'warehouse_id' => $stock->id,
'deducted_qty' => $toDeduct,
'reason' => 'order_placement'
]);
});
$requestedQty -= $toDeduct;
}
if ($requestedQty > 0) {
throw new \Exception("库存不足:还需 {$requestedQty} 件,但可用库存已耗尽");
}⚠️ 关键注意事项
- 必须加数据库事务:防止并发请求导致重复扣减或状态不一致;
- 排序字段需业务可靠:id_order 须能反映实际优先级(如入库时间、订单创建时间),避免使用无序主键;
- 前置校验不可省略:应在扣减前通过 SUM(quantita_restante) 验证总库存是否充足,提升响应效率;
- 避免 N+1 查询:上述代码中 decrement() 已为单条 SQL,无需额外 save();
- 并发安全增强:高并发场景下,可结合 SELECT ... FOR UPDATE 锁定待处理记录(Laravel 9+ 支持 sharedLock() / lockForUpdate())。
? 优化思路:预判大单直扣(可选)
若大部分订单量较小,但偶有大单,可先检查最大单条余量是否足够,减少循环开销:
$maxStock = Warehouse::where('id_restaurant', $restaurantId)
->where('id_wine', $wineId)
->where('quantita_restante', '>', 0)
->orderByDesc('quantita_restante')
->first();
if ($maxStock && $maxStock->quantita_restante >= $requestedQty) {
$maxStock->decrement('quantita_restante', $requestedQty);
} else {
// 执行上述循环扣减逻辑
}该方案兼顾准确性、可读性与扩展性,是处理“分布式库存”场景的稳健实践。










