在实体的存储库中,我想获取具有给定 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/