克隆包含所有关系的雄辩对象?

问题描述 投票:57回答:9

有没有办法轻松克隆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');
    }
}
laravel laravel-4 clone eloquent
9个回答
46
投票

在laravel 4.2中测试了belongsToMany的关系

如果你在模特中:

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

51
投票

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

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

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

24
投票

你可以试试这个(Object Cloning):

$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手动复制。

此外,您需要注意这一点,如果您不使用roles加载with,那么这些将不会加载或在$user中不可用,当您调用$user->roles时,那些对象将在运行时加载在$user->roles召唤之后的时间,直到这个,那些roles没有加载。

更新:

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

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

15
投票

对于Laravel 5.使用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());
    }
}

6
投票

以下是来自@ 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();
        }
    }

3
投票

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

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

此代码适用于laravel 5。


2
投票

这是在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 launched

现在可以使用复制

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

1
投票

当您通过任何您想要的关系获取对象,并在此之后复制时,您复制的所有关系也会被复制。例如:

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

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的映射,然后重新同步。

© www.soinside.com 2019 - 2024. All rights reserved.