Symfony 2 - Clone entity with one to many sonata media relationship

一笑奈何 提交于 2020-01-01 19:18:05

问题


I have a Product entity with a one to many relationship with the media entity

/**
* @ORM\OneToMany(targetEntity="Norwalk\StoreBundle\Entity\ProductHasMedia", mappedBy="product", cascade={"persist"}, orphanRemoval=true )
*/
protected $imagenes;

And a one to one relationship with a Package entity

/**
* @ORM\OneToOne(targetEntity="Package", cascade={"persist"})
* @ORM\JoinColumn(name="package", referencedColumnName="id")
*/
protected $package;

I am able to clone the Product entity with this function

public function __clone() {
        if ($this->id) {
            $this->package = clone $this->package;
        }
        // Get current collection
        $imagenes = $this->getImagenes();
        $this->imagenes = new ArrayCollection();
        if(count($imagenes) > 0){
            foreach ($imagenes as $imagen) {
                $cloneImagen = clone $imagen;
                $this->imagenes->add($cloneImagen);
                $cloneImagen->setProduct($this);
            }
        } 
}

The problem is, that the new entity has associated the same images as the original entity. This means if I delete the image in one entity, it is deleted on the other too. See table below, where original product (with id 5) has the same media as cloned product (with id 7)

What I need, is that these cloned images have a new ID and I I need them to be not related with the original entity, sofor example, when I delete some images from the cloned entity, it will not affect to the original entity.

Any ideas? :)

Thanks in advance


回答1:


You forget that all your manipulations must be inside if ($this->id) block:

public function __clone() {
    if ($this->id) {
        $this->package = clone $this->package;
        $imagenes = $this->getImagenes();
        $this->imagenes = new ArrayCollection();
        if(count($imagenes) > 0){
            foreach ($imagenes as $imagen) {
                $cloneImagen = clone $imagen;
                $this->imagenes->add($cloneImagen);
                $cloneImagen->setProduct($this);
            }
        } 
    }
}

Also if you have some links in your Norwalk\StoreBundle\Entity\ProductHasMedia class then you should implement __clone() with managing appropriate fields in this entity too.



来源:https://stackoverflow.com/questions/28311805/symfony-2-clone-entity-with-one-to-many-sonata-media-relationship

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!