Symfony 2 - 具有一对多奏鸣曲媒体关系的克隆实体 [英] Symfony 2 - Clone entity with one to many sonata media relationship

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

问题描述

我有一个 Product 实体,它与媒体实体具有一对多关系

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

/**
* @ORMOneToMany(targetEntity="NorwalkStoreBundleEntityProductHasMedia", mappedBy="product", cascade={"persist"}, orphanRemoval=true )
*/
protected $imagenes;

与包实体一对一的关系

/**
* @ORMOneToOne(targetEntity="Package", cascade={"persist"})
* @ORMJoinColumn(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);
            }
        } 
}

问题是,新实体关联了与原始实体相同的图像.这意味着如果我删除一个实体中的图像,它也会在另一个实体中被删除.请参见下表,其中原始产品(id 为 5)与克隆产品(id 为 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,并且需要它们与原始实体无关,例如,当我从克隆的实体中删除一些图像时,它不会影响到原始实体.

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.

有什么想法吗?:)

提前致谢

推荐答案

你忘记了所有的操作都必须在 if ($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);
            }
        } 
    }
}

此外,如果您的 NorwalkStoreBundleEntityProductHasMedia 类中有一些链接,那么您也应该实现 __clone() 并管理该实体中的相应字段.

Also if you have some links in your NorwalkStoreBundleEntityProductHasMedia class then you should implement __clone() with managing appropriate fields in this entity too.

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

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