Doctrine detaching, caching, and merging

前端 未结 1 1126
情深已故
情深已故 2021-01-02 07:29

I\'m on Doctrine 2.3. I have the following query:

$em->createQuery(\'
    SELECT u, c, p
    FROM Entities\\User u
    LEFT JOIN u.company c
    LEFT JOI         


        
相关标签:
1条回答
  • 2021-01-02 08:17

    When merging a User, you want the associated Company and Privilege to be merged as well, correct?

    This process is called cascading:

    http://docs.doctrine-project.org/projects/doctrine-orm/en/latest/reference/working-with-associations.html#transitive-persistence-cascade-operations

    In your User entity put cascade={"merge"} in the @ManyToOne annotation (or another type of association-definition you are using) for $company and $privilege.

    And if you want the detach call to be cascaded too (which is recommended), put in cascade={"detach", "merge"}.

    p.s.: Don't put such cascades on both sides of one association, you'll create an endless loop ;)

    Edit:

    This piece of code:

    $entity = $cacheDriver->fetch($cacheId);
    $em->merge($entity);                      // <-
    return $entity;
    

    should be:

    $entity = $cacheDriver->fetch($cacheId);
    $entity = $em->merge($entity);            // <-
    return $entity;
    

    The thing with merge() is that it leaves the entity you pass as an argument untouched, and returns a new object that represents the managed version of the entity. So you want to use the return-value, not the argument you passed.

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