zend-framework2 - zend framework 2 with doctrine,如何在 Entitymanager 被异常关闭后重新打开

标签 zend-framework2 zfdoctrine

在实体的存储库中,我想获取具有给定 ID 的实体或创建一个新实体(如果给定 ID 到目前为止未被使用)。我的解决方案是,创建一个带有 id 的新实体。如果可能的话,我会返回,如果不可能,我想加载现有的。非常糟糕,这是不可能的,因为实体管理器已关闭。

class TestRepository extends Repository {

    // create a new entity or load the existing one
    public function getEntity($pkey) {
        $entity = new Entity($pkey); // create a new entity and set its id to $pkey
        $this->getEntityManager()->persist($language);
        try {
            $this->getEntityManager()->flush(); // success if $pkey isn't used
        } catch (DBALException $e) {
            // this DBALException is catched correct
            // fail - load the existing one
            $entity = $this->find(array($pkey)); // another exception is thrown
            // The EntityManager is closed.
        }
        return $entity;
    }

}

如何重新打开 EntityManger?

最佳答案

为什么要尝试使用定义的主键来持久化实体,而您从中不知道它是否存在?

首先创建一个简单的 find() 是合适的,如果它没有返回结果,您可以创建您的实体并持久化它。

希望这对您有所帮助。

关于zend-framework2 - zend framework 2 with doctrine,如何在 Entitymanager 被异常关闭后重新打开,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17369570/

相关文章:

facebook - 适用于 Facebook、Twitter 和 Google + 的 Zend 2 身份验证

php - 何时使用 tablegateway 和 Adapter

php - 在 Zend Framework 2 Select 中左连接变量

zend-framework2 - Zend Framework 2 - 如何更改 Controller 插件中的 View 脚本?

php - Zend Framework 2 phpunit 测试带有连接的表

doctrine-orm - ZF2 inputfilter 主义 NoObjectExists 编辑对象不验证

php - Doctrine2 QB OneToMany 连接上的语义错误