id = $task->id; $dto->categoryId = $task->category_id; $dto->name = $task->name; $dto->description = $task->description; $dto->type = $task->type; $dto->prerequisiteTasks = $task->prerequisite_tasks ?? []; $dto->levelRequired = $task->level_required ?? 1; $dto->timeLimit = $task->time_limit; $dto->maxCompletions = $task->max_completions; $dto->resetType = $task->reset_type ?? 'none'; $dto->displayParams = $task->display_params ?? []; $dto->sortOrder = $task->sort_order ?? 0; $dto->isActive = (bool)$task->is_active; $dto->startTime = $task->start_time ? $task->start_time->format('Y-m-d H:i:s') : null; $dto->endTime = $task->end_time ? $task->end_time->format('Y-m-d H:i:s') : null; // 加载任务奖励 if ($task->relationLoaded('rewards')) { foreach ($task->rewards as $reward) { $dto->rewards[] = TaskRewardDto::fromModel($reward); } } // 加载任务条件 if ($task->relationLoaded('achievementConditions')) { foreach ($task->achievementConditions as $condition) { $dto->conditions[] = TaskConditionDto::fromModel($condition); } } return $dto; } /** * 从数组创建DTO * * @param array $data 数据数组 * @return static */ public static function fromArray(array $data): static { $dto = parent::fromArray($data); // 处理奖励数组 if (isset($data['rewards']) && is_array($data['rewards'])) { $dto->rewards = []; foreach ($data['rewards'] as $reward) { $dto->rewards[] = TaskRewardDto::fromArray($reward); } } // 处理条件数组 if (isset($data['conditions']) && is_array($data['conditions'])) { $dto->conditions = []; foreach ($data['conditions'] as $condition) { $dto->conditions[] = TaskConditionDto::fromArray($condition); } } return $dto; } /** * 转换为模型数据数组 * * @return array */ public function toModelArray(): array { return [ 'id' => $this->id ?? null, 'category_id' => $this->categoryId, 'name' => $this->name, 'description' => $this->description, 'type' => $this->type, 'prerequisite_tasks' => $this->prerequisiteTasks, 'level_required' => $this->levelRequired, 'time_limit' => $this->timeLimit, 'max_completions' => $this->maxCompletions, 'reset_type' => $this->resetType, 'display_params' => $this->displayParams, 'sort_order' => $this->sortOrder, 'is_active' => $this->isActive, 'start_time' => $this->startTime, 'end_time' => $this->endTime, ]; } }