2016-03-15 82 views
4

我有一個複製我的模型與所有關係的問題。Laravel雄辯的ORM複製

數據庫結構如下:

Table1: products 
id 
name 

Table2: product_options 
id 
product_id 
option 

Table3: categories 
id 
name 

Pivot table: product_categories 
product_id 
category_id 

關係是:

  • 產品的hasMany product_options
  • 產物belongsToMany類別(波谷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(); 
} 

但這不起作用(關係不克隆 - 目前我只是試圖克隆product_options)。

+1

這個答案:http://stackoverflow.com/questions/23895126/clone-an-eloquent-object-including-all-relationships#answer-34032304和這樣的回答:http://stackoverflow.com/問題/ 23895126/clone-an-eloquent-object-including-all-relationships#answer-32775847爲我工作 – haakym

+1

您可以將您的評論移至答案嗎? – Zoli

回答

4

此代碼,爲我工作:從這裏

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

答:Clone an Eloquent object including all relationships?

這個答案(同樣的問題)也,也很好。

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

從這裏:Clone an Eloquent object including all relationships?

代碼爲許多人在我的經驗,許多關係工作正常。

2

嘗試使用attach創建關係:

foreach($product->options as $option){ 
    $new_option = $option->replicate(); 
    $new_option->save(); 
    $new_option_id = $new_option->id; 
    $new_product->options()->attach($new_option_id); 
} 
1
$product = Product::with('options')->find($id); 
$new_product = $product->replicate(); 
$new_product->{attribute} = {value}; 
$new_product->push(); 

$new_product->options()->saveMany($product->options); 
+2

您應該解釋您的答案,以便提問者(以及任何發現它的人)瞭解此代碼的作用。 – Machavity