validate([ 'member_id' => ['required', 'integer', 'exists:users,member_id'], 'activity_id' => ['required', 'integer'], ]); $memberId = request()->input('member_id'); if (ActivityUser::where('member_id', $memberId)->where('status', 0)->exists()) { throw new Exception('完成活动才可以参与新活动', HttpStatus::CUSTOM_ERROR); } $activityId = request()->input('activity_id'); if (ActivityUser::where('member_id', $memberId)->where('activity_id', $activityId)->exists()) { throw new Exception('已参与过此活动,每个活动仅可参加一次', HttpStatus::CUSTOM_ERROR); } $time = time(); $activity = ActivityRewardService::findOne([ 'start_time' => ['<=', $time], 'end_time' => ['>=', $time], 'status' => ActivityRewardModel::STATUS_UP, 'id' => $activityId ]); if (!$activity) throw new Exception('活动不存在', HttpStatus::CUSTOM_ERROR); ActivityUser::create([ 'activity_id' => $activityId, 'title' => $activity->title, 'sub_title' => $activity->sub_title, 'start_time' => $activity->start_time, 'end_time' => $activity->end_time, 'detail_image' => $activity->detail_image, 'part_in_time' => $time, 'member_id' => $memberId, 'status' => 0 ]); } catch (ValidationException $e) { return $this->error($e->validator->errors()->first()); } catch (Exception $e) { return $this->error($e->getMessage()); } return $this->success($activity); } public function index(): JsonResponse { try { request()->validate(['member_id' => ['nullable', 'integer']]); $memberId = request()->input('member_id'); $time = time(); $query = ActivityRewardModel::where(ActivityRewardService::getWhere([ 'start_time' => ['<=', $time], 'end_time' => ['>=', $time], 'status' => ActivityRewardModel::STATUS_UP ])); if (!empty($memberId)) { $query->with(['activityUser' => function ($query1) use ($memberId) { $query1->where('member_id', $memberId); }]); } $list = $query->orderByDesc('id')->get(); $list->transform(function ($activity) use ($memberId) { if (!empty($memberId)) { $activity->is_claimed = $activity->activityUser->isNotEmpty(); } else { $activity->is_claimed = false; } unset($activity->activityUser); return $activity; })->toArray(); } catch (ValidationException $e) { return $this->error($e->validator->errors()->first()); } catch (Exception $e) { return $this->error($e->getMessage()); } return $this->success($list); } }