getLandId(); $userItemId = $data->getItemId(); $userId = $this->user_id; // 先进行验证,避免不必要的事务开销 $validation = new \App\Module\Farm\Validations\DisasterRemovalValidation([ 'user_id' => $userId, 'land_id' => $landId, 'item_id' => $userItemId, 'disaster_type' => DISASTER_TYPE::DROUGHT->value ]); // 验证数据 $validation->validated(); // 验证通过后,开启事务 DB::beginTransaction(); // 执行业务逻辑(不再需要验证) $result = CropService::removeDisasterWithItem( $userId, $landId, $userItemId, DISASTER_TYPE::DROUGHT->value, 'land_watering' ); // 提交事务 DB::commit(); // 设置响应状态 $this->response->setCode(RESPONSE_CODE::OK); $this->response->setMsg($result['message']); } catch (\Exception $e) { // 系统异常,需要回滚事务 if (DB::transactionLevel() > 0) { DB::rollBack(); } Log::error('浇水操作异常', [ 'user_id' => $this->user_id, 'land_id' => $landId ?? null, 'item_id' => $userItemId ?? null, 'error' => $e->getMessage(), 'trace' => $e->getTraceAsString() ]); // 重新抛出异常,交由框架处理 throw $e; } return $response; } }