克隆一个雄辩的对象,包括所有关系?


86

有什么方法可以轻松克隆Eloquent对象,包括其所有关系吗?

例如,如果我有这些表:

users ( id, name, email )
roles ( id, name )
user_roles ( user_id, role_id )

除了在users表中创建新行(除以外的所有列均相同)之外 id,还应在user_roles表中创建新行,并将相同的角色分配给新用户。

像这样:

$user = User::find(1);
$new_user = $user->clone();

用户模型所在的位置

class User extends Eloquent {
    public function roles() {
        return $this->hasMany('Role', 'user_roles');
    }
}

Answers:


74

在laravel 4.2中进行了测试,证明是否为ManyToMany关系

如果您在模型中:

    //copy attributes
    $new = $this->replicate();

    //save model before you recreate relations (so it has an id)
    $new->push();

    //reset relations on EXISTING MODEL (this way you can control which ones will be loaded
    $this->relations = [];

    //load relations on EXISTING MODEL
    $this->load('relation1','relation2');

    //re-sync everything
    foreach ($this->relations as $relationName => $values){
        $new->{$relationName}()->sync($values);
    }

3
在Laravel 7工作
Daniyal Javani

它也可以在早期版本的Laravel 6上运行。
mmmdearte

在Laravel 7.28.4中工作。我已经注意到,如果您试图在模型外部运行代码,则代码应该有所不同。谢谢
Roman Grinev

56

您也可以尝试雄辩的提供的复制功能:

http://laravel.com/api/4.2/Illuminate/Database/Eloquent/Model.html#method_replicate

$user = User::find(1);
$new_user = $user->replicate();
$new_user->push();

7
实际上,您还必须加载要复制的关系。给定的代码将仅复制基本模型而没有其关系。要克隆关系,也可以让用户了解其关系:$user = User::with('roles')->find(1);或者在拥有模型后加载它们:因此,前两行是$user = User::find(1); $user->load('roles');
Alexander Taubenkorb 2015年

2
加载关系似乎也不会复制关系,至少在4.1中不会。我必须复制父代,然后遍历原始复制子代的子代,并一次更新一个以指向新父代。
雷克斯·施拉德

replicate()将建立关系并push()递归到关系中并保存它们。
Matt K

同样在5.2中,您需要遍历子级并在一次复制一个子级之后将其保存;内foreach:$new_user->roles()->save($oldRole->replicate)
d.grassi84 '16

28

您可以尝试以下操作(对象克隆):

$user = User::find(1);
$new_user = clone $user;

由于clone不会进行深度复制,因此如果有可用的子对象,则不会复制子对象,在这种情况下,您需要clone手动复制子对象。例如:

$user = User::with('role')->find(1);
$new_user = clone $user; // copy the $user
$new_user->role = clone $user->role; // copy the $user->role

在您的情况下,roles将是一个Role对象集合,因此Role object需要使用手动复制集合中的每个对象clone

另外,您需要注意的是,如果您不加载rolesusing,with那么这些将不会在中加载或不可用,$user并且当您调用时,$user->roles这些对象将在调用后的运行时加载的$user->roles,直到这一点,那些roles不加载。

更新:

这个答案是针对的Larave-4,现在Laravel提供了replicate()方法,例如:

$user = User::find(1);
$newUser = $user->replicate();
// ...

2
注意,仅是浅表副本,而不是子/子对象:-)
Alpha

1
@TheShiftExchange,您可能会发现它很有趣,我很久以前做了一个实验。感谢您的赞许:-)
Alpha

1
这不是还复制对象的ID吗?使它无济于事吗?
Tosh

@Tosh,是的,正是那为什么你需要设置另一个ID或的null:-)
阿尔法

1
plus1揭示了php的秘密:P
代谢

21

对于Laravel5。已测试hasMany关系。

$model = User::find($id);

$model->load('invoices');

$newModel = $model->replicate();
$newModel->push();


foreach($model->getRelations() as $relation => $items){
    foreach($items as $item){
        unset($item->id);
        $newModel->{$relation}()->create($item->toArray());
    }
}

7

这是@ sabrina-gelbart提供的解决方案的更新版本,它将克隆所有hasMany关系,而不仅仅是她所发布的belongsToMany:

    //copy attributes from original model
    $newRecord = $original->replicate();
    // Reset any fields needed to connect to another parent, etc
    $newRecord->some_id = $otherParent->id;
    //save model before you recreate relations (so it has an id)
    $newRecord->push();
    //reset relations on EXISTING MODEL (this way you can control which ones will be loaded
    $original->relations = [];
    //load relations on EXISTING MODEL
    $original->load('somerelationship', 'anotherrelationship');
    //re-sync the child relationships
    $relations = $original->getRelations();
    foreach ($relations as $relation) {
        foreach ($relation as $relationRecord) {
            $newRelationship = $relationRecord->replicate();
            $newRelationship->some_parent_id = $newRecord->id;
            $newRelationship->push();
        }
    }

some_parent_id并非所有关系都一样棘手。不过,这很有用,谢谢。
达斯汀·格雷厄姆

4

这是在laravel 5.8中,还没有在旧版本中尝试过

//# this will clone $eloquent and asign all $eloquent->$withoutProperties = null
$cloned = $eloquent->cloneWithout(Array $withoutProperties)

编辑,就在今天2019年4月7日,laravel 5.8.10发布

现在可以使用复制

$post = Post::find(1);
$newPost = $post->replicate();
$newPost->save();

2

如果您有一个名为$ user的集合,则使用下面的代码,它将创建一个与旧集合相同的新Collection,包括所有关系:

$new_user = new \Illuminate\Database\Eloquent\Collection ( $user->all() );

该代码适用于laravel 5。


1
你可以不做$new = $old->slice(0)吗?
fubar

2

当您通过所需的任何关系获取对象并进行复制之后,所获取的所有关系也会被复制。例如:

$oldUser = User::with('roles')->find(1);
$newUser = $oldUser->replicate();

我已经在Laravel 5.5中进行了测试
elyas.m,

2

这是一个特征,它将以递归方式复制对象上所有已加载的关系。您可以轻松地将此扩展为其他关系类型,例如Sabrina的belongsToMany示例。

trait DuplicateRelations
{
    public static function duplicateRelations($from, $to)
    {
        foreach ($from->relations as $relationName => $object){
            if($object !== null) {
                if ($object instanceof Collection) {
                    foreach ($object as $relation) {
                        self::replication($relationName, $relation, $to);
                    }
                } else {
                    self::replication($relationName, $object, $to);
                }
            }
        }
    }

    private static function replication($name, $relation, $to)
    {
        $newRelation = $relation->replicate();
        $to->{$name}()->create($newRelation->toArray());
        if($relation->relations !== null) {
            self::duplicateRelations($relation, $to->{$name});
        }
    }
}

用法:

//copy attributes
$new = $this->replicate();

//save model before you recreate relations (so it has an id)
$new->push();

//reset relations on EXISTING MODEL (this way you can control which ones will be loaded
$this->relations = [];

//load relations on EXISTING MODEL
$this->load('relation1','relation2.nested_relation');

// duplication all LOADED relations including nested.
self::duplicateRelations($this, $new);

0

如果其他解决方案不能使您满意,这是另一种方法:

<?php
/** @var \App\Models\Booking $booking */
$booking = Booking::query()->with('segments.stops','billingItems','invoiceItems.applyTo')->findOrFail($id);

$booking->id = null;
$booking->exists = false;
$booking->number = null;
$booking->confirmed_date_utc = null;
$booking->save();

$now = CarbonDate::now($booking->company->timezone);

foreach($booking->segments as $seg) {
    $seg->id = null;
    $seg->exists = false;
    $seg->booking_id = $booking->id;
    $seg->save();

    foreach($seg->stops as $stop) {
        $stop->id = null;
        $stop->exists = false;
        $stop->segment_id = $seg->id;
        $stop->save();
    }
}

foreach($booking->billingItems as $bi) {
    $bi->id = null;
    $bi->exists = false;
    $bi->booking_id = $booking->id;
    $bi->save();
}

$iiMap = [];

foreach($booking->invoiceItems as $ii) {
    $oldId = $ii->id;
    $ii->id = null;
    $ii->exists = false;
    $ii->booking_id = $booking->id;
    $ii->save();
    $iiMap[$oldId] = $ii->id;
}

foreach($booking->invoiceItems as $ii) {
    $newIds = [];
    foreach($ii->applyTo as $at) {
        $newIds[] = $iiMap[$at->id];
    }
    $ii->applyTo()->sync($newIds);
}

诀窍是擦除idexists属性,以便Laravel创建新记录。

克隆自我关系有些棘手,但我已经举了一个例子。您只需创建旧ID到新ID的映射,然后重新同步即可。

By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.