在实体的存储库中,如果到目前为止未使用给定的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?
答案 0 :(得分:0)
为什么要尝试使用已定义的主键来保留实体,但不知道它是否存在?
首先制作一个简单的find()并且如果它没有返回任何结果,你就可以创建你的实体并保持它。
穆罕默德。