getReference() of doctrine Entity Manager

前端 未结 3 1886
时光说笑
时光说笑 2020-12-30 08:55

Situation:

I want to use the getReference() function of doctrine2 Entity Manager. However, in a situation where I ask for an object that has been deleted from the

相关标签:
3条回答
  • 2020-12-30 09:41

    You need get reference and check if contains on database:

    $classChild = $this->doctrine->getReference($classReference, $id);                                
    if (!$this->doctrine->contains($classChild)) {
        throw new \Exception("Invalid Reference");
    }
    

    Where $this->doctrine is your EntityManager

    0 讨论(0)
  • 2020-12-30 09:47

    There is no way to make getReference() check the database for the existence of the referenced object.

    Actually, this is what getReference() and the proxies returned by it are all about: Creating placeholder objects (proxies) without going to the database. And you would rarely want to do that explicitly. Normally Doctrine does this internally when hydrating entities to create lazy loading placeholders for related entities based on foreign key values.

    Why don't you just call find() on the Entity Manager? Are you aware that the EM will not query the DB more than once for the same object as long as you look it up by ID? Doctrine keeps track of already hydrated objects in the Unit Of Work and returns references to the existing objects in subsequent find() calls.

    0 讨论(0)
  • 2020-12-30 09:59

    If you use getReference to get an object, but then call a method on it such as getName then Doctrine will fetch the entity from the DB. It has no other way to find out the property (getName).


    Concerning your challenge:

    EntityManager->contains($entity) would be the preferred way to check if the entity from doctrine is in the entity manager

    0 讨论(0)
提交回复
热议问题