Symfony 2 - 具有一对多声纳介质关系的克隆实体 [英] Symfony 2 - Clone entity with one to many sonata media relationship

查看:93
本文介绍了Symfony 2 - 具有一对多声纳介质关系的克隆实体的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个与媒体实体有一对多关系的产品实体

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;

与包实体的一对一关系

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

我可以使用此功能克隆Product实体

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);
            }
        } 
}

问题是,新实体已经将与原始实体相同的图像相关联。这意味着如果我删除一个实体中的图像,它也被删除。请参见下表,其中原始产品(标识为5)与克隆产品具有相同的媒体(带有7)。

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)

我需要的是,这些克隆的图像有一个新的ID,II需要它们与原始实体无关,因此,当我从克隆的实体中删除一些图像时,它不会影响原始实体。

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.

任何想法? :

提前感谢

推荐答案

如果($ this-> id)阻止:

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);
            }
        } 
    }
}

另外如果您在 Norwalk\StoreBundle\Entity\ProductHasMedia 类中有一些链接,那么您应该实现 __ clone()在该实体中管理相应的字段。

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.

这篇关于Symfony 2 - 具有一对多声纳介质关系的克隆实体的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆