targetId; // 宠物配置ID或宠物类型 $petCount = $item->quantity > 0 ? $item->quantity : 1; // 宠物数量,默认1只 $petGrade = $item->param1 > 0 ? $item->param1 : null; // 宠物品阶,为null时随机生成 // 验证宠物配置是否存在 $petConfig = \App\Module\Pet\Models\PetConfig::find($petConfigId); if (!$petConfig) { throw new Exception("宠物配置不存在,配置ID: {$petConfigId}"); } // 循环创建宠物(支持一次奖励多只宠物) $createdPets = []; for ($i = 0; $i < $petCount; $i++) { // 生成宠物名称 $petName = self::generatePetName($petConfig->name, $i + 1, $petCount); // 创建宠物 $result = \App\Module\Pet\Services\PetService::createPet($userId, $petName, $petGrade, [ 'pet_type' => $petConfig->pet_type, 'source' => 'reward', 'source_type' => $sourceType, 'source_id' => $sourceId ]); if (!$result['success']) { throw new Exception("宠物创建失败: " . ($result['message'] ?? '未知错误')); } $createdPets[] = [ 'pet_id' => $result['pet_id'], 'name' => $petName, 'grade' => $result['grade'] ]; Log::info("宠物奖励创建成功", [ 'userId' => $userId, 'petId' => $result['pet_id'], 'petName' => $petName, 'petGrade' => $result['grade'], 'petConfigId' => $petConfigId, 'petType' => $petConfig->pet_type, 'index' => $i + 1, 'totalCount' => $petCount, 'sourceType' => $sourceType, 'sourceId' => $sourceId ]); } Log::info("宠物奖励发放完成", [ 'userId' => $userId, 'petConfigId' => $petConfigId, 'petType' => $petConfig->pet_type, 'petCount' => $petCount, 'petGrade' => $petGrade, 'createdPets' => $createdPets, 'sourceType' => $sourceType, 'sourceId' => $sourceId ]); } catch (Exception $e) { Log::error("宠物奖励发放失败", [ 'userId' => $userId, 'petConfigId' => $item->targetId, 'petCount' => $item->quantity, 'petGrade' => $item->param1, 'sourceType' => $sourceType, 'sourceId' => $sourceId, 'error' => $e->getMessage() ]); throw new Exception("宠物奖励发放失败: " . $e->getMessage()); } } /** * 生成宠物名称 * * @param string $baseName 基础名称 * @param int $index 索引 * @param int $total 总数 * @return string 生成的宠物名称 */ private static function generatePetName(string $baseName, int $index, int $total): string { if ($total == 1) { return $baseName; } return $baseName . $index; } }