Reputation: 39
Within an entity's repository, I want to fetch the entity with a given id or create a new one, if the given id is not used so far. My solution is, to create a new entity with the id. If it is possible I return it, if not I want to load the excisting one. Very bad, that it is not possible, cause the entitymanager is closed.
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;
}
}
How can I reopen the EntityManger?
Upvotes: 3
Views: 626
Reputation: 2214
Why do you try to persist an entity with a defined primary key from which you do not know if it yet exists?
It would be suitable to make a simple find() first and if it returns no result, you create your entity and persists it.
Hope this helps.
Upvotes: 0