Laravel Eloquent ORM复制

Zol*_*oli 6 php clone relationship laravel eloquent

我在使用所有关系复制我的一个模型时遇到问题.

数据库结构如下:

Table1: products
id
name

Table2: product_options
id
product_id
option

Table3: categories
id
name

Pivot table: product_categories
product_id
category_id
Run Code Online (Sandbox Code Playgroud)

关系是:

  • 产品有很多product_options
  • 产品属于多种类别(槽product_categories)

我想克隆一个包含所有关系的产品.目前这是我的代码:

$product = Product::with('options')->find($id);
$new_product = $product->replicate();
$new_product->push();
foreach($product->options as $option){
    $new_option = $option->replicate();
    $new_option->product_id = $new_product->id;
    $new_option->push();
}
Run Code Online (Sandbox Code Playgroud)

但这不起作用(关系没有被克隆 - 目前我只是试图克隆product_options).

haa*_*kym 10

这段代码对我有用:

$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());
    }
}
Run Code Online (Sandbox Code Playgroud)

从这里回答:克隆一个包含所有关系的雄辩对象?

这个答案(同样的问题),也可以正常工作.

//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();
    }
}
Run Code Online (Sandbox Code Playgroud)

从这里:克隆一个包含所有关系的雄辩对象?

根据我的经验,代码适用于多对多的关系.