getLandId(); $itemId = $data->getItemId(); $userId = $this->user_id; Log::info('施肥操作开始', [ 'user_id' => $userId, 'land_id' => $landId, 'item_id' => $itemId, ]); // 先进行验证,避免不必要的事务开销 Log::info('FertilizerHandler: 开始验证', [ 'user_id' => $userId, 'land_id' => $landId, 'item_id' => $itemId, ]); $validationData = [ 'user_id' => $userId, 'land_id' => $landId, 'item_id' => $itemId, ]; $validation = new FertilizerValidation($validationData); $validation->validated(); // 这个方法会在验证失败时抛出异常 try { // 验证通过后,开启事务 DB::beginTransaction(); // 从验证结果中获取数据,避免重复查询 $cropGrowthTime = $validation->crop_growth_time; $crop = $validation->crop; // 从验证结果中获取作物对象 $cropId = $crop->id; // 获取作物ID Log::info('FertilizerHandler: 验证通过,获取到作物信息', [ 'user_id' => $userId, 'land_id' => $landId, 'crop_id' => $cropId, 'crop_growth_time' => $cropGrowthTime, ]); // 使用肥料(直接传入作物ID) $result = CropService::useFertilizer($cropId, $cropGrowthTime); if ($result->error) { throw new LogicException("施肥失败:" . $result->message); } // 消耗物品 ItemService::consumeItem($userId, $itemId, null, 1, [ 'source_type' => 'land_fertilizer', 'source_id' => $landId, 'details' => ['land_id' => $landId, 'crop_id' => $cropId] ]); // 提交事务 DB::commit(); Log::info('施肥操作成功', [ 'user_id' => $userId, 'land_id' => $landId, 'item_id' => $itemId, 'crop_id' => $cropId, 'crop_growth_time' => $cropGrowthTime, ]); // 更新作物生长阶段(在事务外执行) CropService::updateGrowthStage($cropId); } catch (\Exception $e) { // 系统异常,需要回滚事务 if (DB::transactionLevel() > 0) { DB::rollBack(); } Log::error('施肥操作异常', [ 'user_id' => $userId, 'land_id' => $landId, 'item_id' => $itemId, 'error' => $e->getMessage(), 'trace' => $e->getTraceAsString() ]); // 重新抛出异常,交由框架处理 throw $e; } return $response; } }