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

时间:2014-05-27 17:05:41

标签: laravel laravel-4 clone eloquent

有没有办法轻松克隆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');
    }
}

10 个答案:

答案 0 :(得分: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();

答案 1 :(得分:42)

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

答案 2 :(得分: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,那么这些内容将无法加载或赢得{ {1}}当您调用$user时,这些对象将在$user->roles调用后的运行时加载,直到此时,这些$user->roles才会被加载。< / p>

更新

这个答案适用于roles,现在Laravel提供Larave-4方法,例如:

replicate()

答案 3 :(得分:14)

对于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());
    }
}

答案 4 :(得分: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();
        }
    }

答案 5 :(得分:3)

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

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

此代码适用于laravel 5.

答案 6 :(得分: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();

答案 7 :(得分: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);

答案 8 :(得分:1)

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

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

答案 9 :(得分: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的映射,然后重新同步。