如何检查多个 类 的学说交易

How to check doctrine transaction over several classes

在我的代码中,我必须保存几个连接的实体。有些具有 OneToMany 关系,因此我将这些实体保存在另一个 class 中。为了能够回滚整个保存过程,我使用 transactions with doctrine。

在 class 处理另一个所依赖的“核心”实体时,我执行以下操作:

        $this->connection->beginTransaction();
        try {
            $this->entityManager->persist($report);
            $this->entityManager->flush();
            $this->entityManager->refresh($report);

            // call to connected entities
            $this->reportTopicManager->update($report, $reportDto);
            $this->imageUploader->uploadImages($report, $reportDto);

            $this->connection->commit();
        } catch (Exception $e) {
            if ($this->connection->isTransactionActive()) {
                $this->connection->rollBack();
            }
            throw $e;
        }

是否必须在已连接的 classes 中执行相同的事务检查? 或者当我在已连接的 [=] 中遇到异常时,所有内容都会回滚吗? 22=]es?

我在另一个项目中做过,但后来我总是不得不额外检查一个事务是否已经开始,这增加了代码的复杂性。所以我想知道这是否有必要,或者是否足以在整个过程中进行一次交易检查。

是的,看来很有必要。如果你不这样做,你可能会 运行 进入这个错误,至少如果你使用 dama/doctrine-test-bundle 进行测试:

https://github.com/dmaicher/doctrine-test-bundle/issues/58

代码现在看起来像这样:

        $selfOpened = false;
        $reportTopics = [];
        if (!$this->connection->isTransactionActive()) {
            $this->connection->beginTransaction();
            $selfOpened = true;
        }
        try {
            .... Do things....

                $reportTopics[] = $reportTopicDto;
            }
            if ($selfOpened) {
                $this->connection->commit();
            }
        } catch (Exception $e) {
            if ($selfOpened) {
                $this->connection->rollBack();
            }
            $this->logError($e->getMessage());
            $message = 'We had boo boo. Didn't work';
            $message .= json_encode($reportTopicDto);
            throw new UnprocessableEntityHttpException($message, $e, 119);
        }