3

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

4

1 回答 1

0

为什么您尝试使用已定义的主键来持久化一个您不知道它是否存在的实体?

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

希望这可以帮助。

于 2014-12-23T14:19:59.083 回答