克隆一个包含所有关系的 Eloquent 对象?

是否有任何方法可以轻松地克隆一个 Eloquent 对象,包括它的所有关系?

例如,如果我有这些表:

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

In addition to creating a new row in the users table, with all columns being the same except id, it should also create a new row in the user_roles table, assigning the same role to the new user.

就像这样:

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

哪里有用户模型

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

You may try this (物体克隆):

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

另外,你需要注意的是,如果你没有使用 with加载 roles,那么这些对象将不会被加载或者在 $user中不可用,当你调用 $user->roles时,这些对象将在运行时在调用 $user->roles之后被加载,直到这时,这些 roles将不会被加载。

更新:

This answer was for Larave-4 and now Laravel offers replicate() method, for example:

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

你也可以试试雄辩的复制功能:

Http://laravel.com/api/4.2/illuminate/database/eloquent/model.html#method_replicate

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

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

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

这是5号幼虫的密码。

在幼虫4.2中测试了多种关系

如果你在模型中:

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

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

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

For Laravel 5. Tested with hasMany relation.

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

如果其他解决方案不能让你满意,这里还有另外一种方法:

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

这是在幼虫5.8,没有尝试在旧版本

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

2019年4月7日

现在可以使用复制了

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

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

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

下面是一个将递归复制对象上所有 已加载关系的 trait。您可以很容易地将其扩展到其他关系类型,比如 Sabrina 的 belsTomany 示例。

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

在 Laravel v5.8.10 + (目前为 Laravel v9.x)中,如果您需要使用 Laravel replicate()模型处理关系,这可能是一个解决方案。让我们看两个简单的例子。

app/Models/Product.php

<?php
  

namespace App\Models;
  

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
  

class Product extends Model
{
use HasFactory;


/**
* The attributes that are mass assignable.
*
* @var array<string>
*/
protected $fillable = [
'name', 'price', 'slug', 'category_id'
];
}

app/Models/Category.php

<?php
  

namespace App\Models;
  

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
  

class Category extends Model
{
use HasFactory;
  

/**
* Get all the products for the Category.
*
* @return \Illuminate\Database\Eloquent\Relations\HasMany
*/
public function products()
{
return $this->hasMany(Product::class);
}
  

/**
* Clone the model into a new, non-existing instance with all the products.
*
* @return \App\Models\Category
*/
public function replicateRow()
{
$clon = $this->replicate();
$clon->push();
       

$this->products->each(
fn ($product) => $clon->products()->create($product->toArray())
);


return $clon;
}
}

Controller Code

<?php
  

namespace App\Http\Controllers;
  

use App\Models\Category;
  

class ReplicateController extends Controller
{
/**
* Handle the incoming request.
*
* @param  \App\Models\Category $category
* @return void
*/
public function index(Category $category)
{
$newCategory = $category->replicateRow();
  

dd($newCategory);
}
}

我在 BaseModel中添加了这个函数来用关系复制数据,它在 Laravel9中工作。

public function replicateWithRelationsAttributes(): static
{
$model = clone $this->replicate();
foreach ($this->getRelations() as $key => $relation) {
$model->setAttribute($key, clone $relation);
}


return $model;
}