Symfony 2 - Clone entity with one to many sonata m

2019-04-15 05:46发布

问题:

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.