具有相关实体的深度克隆教义实体 [英] Deep clone Doctrine entity with related entities

查看:28
本文介绍了具有相关实体的深度克隆教义实体的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我创建了一个实体 AOneToManyB 的关系,其中 OneToMany 有关系>C.

I have created an entity A with OneToMany relation to B, which have relation OneToMany to C.

我必须克隆这个 A 实体并用新的 id 将它设置在数据库中.此外,所有深层关系也应使用新 ID 进行克隆.

I have to clone this A entity and set it in database with new id. Also all deep relations should be cloned with new ids too.

我尝试的是将 A id 设置为 null:

What have I tried is to set A id to null:

$A = clone $A_original;
$A->setId(null);
$em->persist($A);

它在 A 表中创建新记录,但不在 BC 中.

It creates new record in A table, but does not in B and C.

我应该怎么做才能制作A实体的完整副本?

What should I do to make a full copy of A entity ?

推荐答案

您必须在实体中实现一个 __clone() 方法,该方法将 id 设置为 null 并根据需要克隆关系.因为如果您将 id 保留在相关对象中,则它假定您的新实体 A 与现有实体 BC 有关系.

You have to implement a __clone() method in your entities that sets the id to null and clones the relations if desired. Because if you keep the id in the related object it assumes that your new entity A has a relation to the existing entities B and C.

A 的克隆方法:

public function __clone() {
    if ($this->id) {
        $this->setId(null);
        $this->B = clone $this->B;
        $this->C = clone $this->C;
    }
}

BC 的克隆方法:

public function __clone() {
    if ($this->id) {
        $this->setId(null);
    }
}

https://groups.google.com/forum/?fromgroups=#!topic/doctrine-user/Nu2rayrDkgQ

https://doctrine-orm.readthedocs.org/en/latest/cookbook/implementing-wakeup-or-clone.html

基于 coder4 的评论,显示了 A 上 OneToMany 关系的克隆方法,其中 $this->M 是 OneToMany,因此是 ArrayCollection:

Based on the comment of coder4show a clone-method for a OneToMany relationship on A where $this->M is OneToMany and therefore an ArrayCollection:

public function __clone() {
    if ($this->id) {
        $this->setId(null);

        // cloning the relation M which is a OneToMany
        $mClone = new ArrayCollection();
        foreach ($this->M as $item) {
            $itemClone = clone $item;
            $itemClone->setA($this);
            $mClone->add($itemClone);
        }
        $this->M = $mClone;
    }
}

这篇关于具有相关实体的深度克隆教义实体的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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