有什么方法可以轻松克隆一个 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 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);
}
你也可以试试 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();
$user = User::with('roles')->find(1);
或在拥有模型后加载它们:因此前两行将是 $user = User::find(1); $user->load('roles');
replicate()
将设置关系并 push()
递归到关系中并保存它们。
$new_user->roles()->save($oldRole->replicate)
对于 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());
}
}
您可以试试这个 (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
对象的集合,因此需要使用 clone
手动复制集合中的每个 Role object
。
此外,您需要注意,如果您不使用 with
加载 roles
,那么这些将不会加载或在 $user
中不可用,并且您何时调用 $user->roles
那么这些对象将在调用 $user->roles
之后在运行时加载,直到此时,那些 roles
才不会加载。
更新:
这个答案是针对 Larave-4
的,现在 Laravel 提供了 replicate()
方法,例如:
$user = User::find(1);
$newUser = $user->replicate();
// ...
null
:-)
这是来自@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
对于所有关系都不相同,则很棘手。不过这很有用,谢谢。
这是在 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();
当您通过所需的任何关系获取对象并在此之后进行复制时,您检索到的所有关系也会被复制。例如:
$oldUser = User::with('roles')->find(1);
$newUser = $oldUser->replicate();
如果你有一个名为 $user 的集合,使用下面的代码,它会创建一个与旧集合相同的新集合,包括所有关系:
$new_user = new \Illuminate\Database\Eloquent\Collection ( $user->all() );
此代码适用于 laravel 5。
$new = $old->slice(0)
吗?
这是一个特征,它将递归地复制对象上所有加载的关系。您可以轻松地将其扩展为其他关系类型,例如 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);
如果其他解决方案不能让您满意,这是另一种方法:
<?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);
}
诀窍是擦除 id
和 exists
属性,以便 Laravel 将创建一条新记录。
克隆自我关系有点棘手,但我举了一个例子。您只需创建旧 ID 到新 ID 的映射,然后重新同步。
$this->replicate
步骤中,关系从旧模型重新分配到新模型,因此后面的步骤将没有关系可以提取,旧模型将被破坏。我可以通过将$this->relations = []
移动为 FIRST 命令来使其工作。此外,sync
似乎不再是一种方法,我能够使用createMany
来达到相同的目的,但是对于某些HasOne
rels 不起作用,所以我不得不扩展HasOne
让create
方法不调用setForeignAttributesForCreate
。