zend框架2,带有原则,如何在Entitymanager被异常关闭后重新打开它



在实体的存储库中,如果到目前为止还没有使用给定的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()比较合适,如果它没有返回结果,则创建实体并将其持久化

希望这能有所帮助。

最新更新