From c0d65f6efb4c0cc9f51e97743a8bde695bd5e757 Mon Sep 17 00:00:00 2001 From: vine_liutk <961510893@qq.com> Date: Thu, 24 Mar 2022 14:15:34 +0800 Subject: [PATCH] =?UTF-8?q?=E8=B0=83=E6=95=B4=E6=B4=BB=E5=8A=A8=E9=A2=86?= =?UTF-8?q?=E5=8F=96?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- app/Services/CouponService.php | 27 +++++++++++++++++++-------- 1 file changed, 19 insertions(+), 8 deletions(-) diff --git a/app/Services/CouponService.php b/app/Services/CouponService.php index 21200aba..dcae3adb 100644 --- a/app/Services/CouponService.php +++ b/app/Services/CouponService.php @@ -8,6 +8,7 @@ use App\Models\ProductPart; use App\Models\ReceivePartCouponLog; use App\Models\User; use App\Models\UserCoupon; +use Illuminate\Database\QueryException; class CouponService { @@ -112,17 +113,27 @@ class CouponService protected function receiveSomeCoupons(User $user, array $coupons, ?int $activityId = null) { $userCoupons = []; - foreach ($coupons as $coupon) { - for ($i = 0; $i < $coupon['num']; $i++) { - $userCoupons[] = self::createUserCouponData($user->id, $coupon['coupon'], $activityId ?? null); - } + foreach ($coupons as $key=> $coupon) { //更新对应券发送量,余量; - $coupon['coupon']->increment('sent', $coupon['num']); - if ($coupon['coupon']->limit > 0) {//限量才减少余量 - $coupon['coupon']->decrement('stock', $coupon['num']); + try { + $canSent = true; + if ($coupon['coupon']->limit > 0) {//限量才减少余量 + $coupon['coupon']->decrement('stock', $coupon['num']); + } + } catch (QueryException $e) { + if (strpos($e->getMessage(), 'Numeric value out of range') !== false) { + $canSent = false; + } else { + throw new $e(); + } + } + if ($canSent) { + for ($i = 0; $i < $coupon['num']; $i++) { + $userCoupons[] = self::createUserCouponData($user->id, $coupon['coupon'], $activityId ?? null); + } + $coupon['coupon']->increment('sent', $coupon['num']); } } - // dd($userCoupons); UserCoupon::insert($userCoupons); }