where('uniacid', UNIACID) ->where('status', 1) ->lock(true) ->value('stock'); if ($skuPrice < $buyInfo['goods_num']) { throw new \Exception('商品 ' . $goods['title'] . ' 库存不足'); } } /** * 下单成功扣减库存 * * @param array $orderItems * @return void */ public function forwardStockSale($orderItems) { foreach ($orderItems as $item) { $snapshoot = $item['snapshoot'] ?? []; $goods_num = $item['count'] ?? 1; $goodsId = $snapshoot['id'] ?? 0; $specType = $snapshoot['spec_type'] ?? 'single'; $skuPriceQuery = SkuPriceModel::where('goods_id', $goodsId) ->where('uniacid', UNIACID); if ($specType == 'single') { $skuPrice = $skuPriceQuery->order('id', 'asc')->find(); } else { $skuPrice = $skuPriceQuery->where('goods_sku_text', $snapshoot['sku_text'] ?? '')->find(); } if ($skuPrice) { // 减少规格库存 SkuPriceModel::where('id', $skuPrice['id']) ->where('uniacid', UNIACID) ->setDec('stock', $goods_num); // 增加规格销量 SkuPriceModel::where('id', $skuPrice['id']) ->where('uniacid', UNIACID) ->setInc('sales', $goods_num); // 增加商品总销量 GoodsModel::where('id', $goodsId) ->where('uniacid', UNIACID) ->setInc('total_sales', $goods_num); // 同步更新商品库存 $this->updateGoodsStock($goodsId, $specType); } } } /** * 订单退款返还库存 * * @param array $orderItems * @return void */ public function backStockSale($orderItems) { foreach ($orderItems as $item) { $snapshoot = $item['snapshoot'] ?? []; $goods_num = $item['count'] ?? 1; $goodsId = $snapshoot['id'] ?? 0; $specType = $snapshoot['spec_type'] ?? 'single'; $skuPriceQuery = SkuPriceModel::where('goods_id', $goodsId) ->where('uniacid', UNIACID); if ($specType == 'single') { $skuPrice = $skuPriceQuery->order('id', 'asc')->find(); } else { $skuPrice = $skuPriceQuery->where('goods_sku_text', $snapshoot['sku_text'] ?? '')->find(); } if ($skuPrice) { // 返还规格库存 SkuPriceModel::where('id', $skuPrice['id']) ->where('uniacid', UNIACID) ->setInc('stock', $goods_num); // 减少规格销量 SkuPriceModel::where('id', $skuPrice['id']) ->where('uniacid', UNIACID) ->setDec('sales', $goods_num); // 减少商品总销量 GoodsModel::where('id', $goodsId) ->where('uniacid', UNIACID) ->setDec('total_sales', $goods_num); // 同步更新商品库存 $this->updateGoodsStock($goodsId, $specType); } } } /** * 更新商品库存 * 单规格:取单一库存(status=1) * 多规格:取所有规格库存之和(status=1) * @param int $goodsId 商品ID * @param string $specType 规格类型:single=单规格,multi=多规格 */ protected function updateGoodsStock($goodsId, $specType = 'single') { $stock = 0; if ($specType == 'single') { $skuPrice = SkuPriceModel::where('goods_id', $goodsId) ->where('uniacid', UNIACID) ->where('status', 1) ->order('id', 'asc') ->find(); if ($skuPrice) { $stock = $skuPrice['stock'] ?? 0; } } else { $totalStock = SkuPriceModel::where('goods_id', $goodsId) ->where('uniacid', UNIACID) ->where('status', 1) ->sum('stock'); $stock = $totalStock ?? 0; } GoodsModel::where('id', $goodsId)->update([ 'stock' => $stock ]); } }