本文介紹了Laravel Eloquent ORM 復制的處理方法,對大家解決問題具有一定的參考價值,需要的朋友們下面隨著小編來一起學習吧!
問題描述
我在使用所有關系復制我的模型之一時遇到問題.
I have a problem with replicating one of my models with all the relationships.
數據庫結構如下:
Table1: products
id
name
Table2: product_options
id
product_id
option
Table3: categories
id
name
Pivot table: product_categories
product_id
category_id
關系是:
- product hasMany product_options
- 產品屬于多類別(通過 product_categories)
我想克隆一個具有所有關系的產品.目前這是我的代碼:
I would like to clone a product with all the relationships. Currently here is my code:
$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).
But this does not works (the relationships are not cloned - currently I just tried to clone the product_options).
推薦答案
這段代碼,對我有用:
$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());
}
}
從這里回答:克隆一個包含所有關系的 Eloquent 對象?
這個答案(同樣的問題),也很好用.
This answer (same question), also works fine too.
//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();
}
}
從這里:克隆一個包含所有關系的 Eloquent 對象?
根據我的經驗,該代碼適用于多對多關系.
The code works fine for many to many relationships in my experience.
這篇關于Laravel Eloquent ORM 復制的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!
【網站聲明】本站部分內容來源于互聯網,旨在幫助大家更快的解決問題,如果有圖片或者內容侵犯了您的權益,請聯系我們刪除處理,感謝您的支持!