Updating (from the inverse side) bidirectional many-to-many relationships in Doctrine 2?

后端 未结 2 683
小鲜肉
小鲜肉 2021-02-09 06:58

Customer is the inverse side of \"keywords/customers\" relationship with Keyword:

/**
 * @ORM         


        
2条回答
  •  长发绾君心
    2021-02-09 07:15

    I use slightly different solution than @gredmo. From doctrine documentation: you can use Orphan Removal when you satisfy this assumption:

    When using the orphanRemoval=true option Doctrine makes the assumption that the entities are privately owned and will NOT be reused by other entities. If you neglect this assumption your entities will get deleted by Doctrine even if you assigned the orphaned entity to another one.

    I have this entity class:

    class Contract {
    /**
     * @ORM\OneToMany(targetEntity="ContractParticipant", mappedBy="contract", cascade={"all"}, orphanRemoval=true)
     **/
    }
    protected $participants;
    

    form processing (pseudo code):

        // $_POST carry the Contract entity values
    
        $received = [];
    
        foreach ($_POST['participants'] as $key => $participant) {
    
            if ((!$relation = $collection->get($key))) {
                // new entity
                $collection[$key] = $relation = $relationMeta->newInstance();
    
            } else {
                // editing existing entity
            }
    
            $received[] = $key;
            $this->mapper->save($relation, $participant);   // map POST data to entity
        }
    
        foreach ($collection as $key => $relation) {
            if ($this->isAllowedRemove() && !in_array($key, $received)) {
                // entity has been deleted
                unset($collection[$key]);
            }
        }
    

    Don't forget to persist the entity end flush. Flush also deletes the removed entities.

        $this->em->persist($entity);
        $this->em->flush();
    

提交回复
热议问题