where('num', '>', 0)->orderBy('id')->limit($this->limit)->get(); $logs = $logs->groupBy('task_id'); foreach ($logs as $taskId => $taskLogs) { $task = CouponSendTask::find($taskId); $coupon = Coupon::find($task->coupon_id); //如果优惠券限量,则获取优惠券余量,只发送前面的人; $failedLogs = collect([]); if ($coupon->limit > 0 && $coupon->stock < ($taskLogs->count() * $task->num)) { $failedLogs = $taskLogs->slice($coupon->stock); $taskLogs = $taskLogs->slice(0, $coupon->stock); } //批量插入用户优惠券 $insertUserCoupons = []; foreach ($taskLogs as $taskLog) { for ($i=0; $i< $taskLog->num; $i++) { $insertUserCoupons[] = CouponService::createUserCouponData($taskLog->user_id, $coupon); } } try { DB::beginTransaction(); count($insertUserCoupons) > 0 && UserCoupon::insert($insertUserCoupons); //更新任务日志状态; CouponTaskLog::whereIn('id', $taskLogs->pluck('id')->toArray())->update(['status'=>2]); $failedLogs->count() == 0 || CouponTaskLog::whereIn('id', $failedLogs->pluck('id')->toArray())->update(['status'=>3, 'remarks'=>'库存余量不足']); //更新任务对应券发送量,余量; $coupon->increment('sent', $taskLogs->count()); if ($coupon->limit > 0) {//限量才减少余量 $coupon->decrement('stock', $taskLogs->count()); } //更新如果是任务最后一批,更新任务状态; $taskTotalnum = CouponTaskLog::where('task_id', $taskId)->where('num', '>', 0)->count(); $taskDidnum = CouponTaskLog::where('task_id', $taskId)->where('num', '>', 0)->where('status', '>', 0)->count(); if ($taskTotalnum == $taskDidnum) { $task->update(['status' => 3]); } DB::commit(); } catch (Throwable $th) { DB::rollBack(); report($th); } } $this->info('执行成功'); sleep(60); } } }