EntityManager 已关闭:我必须先检查所有内容吗?

pop*_*_up 4 php doctrine symfony

在很多框架中,当您在数据库中执行请求时,您可以捕获数据库错误以抛出“用户友好”错误。

当我使用学说时,例如我插入重复值时,我收到消息“EntityManager 已关闭”并且无法继续

在尝试在学说中创建实体之前,我们是否总是必须检查重复项、外键?

例如,我在一个服务中这样做:

...
foreach ($reponse as $item) {
    $item = new Item();
    $item->setRelationId(item->id);
    $item->setValue($item->value);
    ...
    try {
        $this->em->persist($item);
        $this->em->flush();
    } catch (\Exception $e) {
        // Useless because if there is an exception, after this the kernel handler ends the transaction
    }
}
Run Code Online (Sandbox Code Playgroud)

简单地用教义来做到这一点的好方法是什么?

谢谢

Ale*_*eri 5

Tou 可以检查是否已关闭,如果是,您可以像这样重新打开它,例如:

   if (!$this->em->isOpen()) {
        $this->em = $this->em->create(
            $this->em->getConnection(),
            $this->em->getConfiguration()
        );
    }
Run Code Online (Sandbox Code Playgroud)