Laravel Eloquent ORM replicate(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 复制的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:Laravel Eloquent ORM 复制
基础教程推荐
- 如何在 XAMPP 上启用 mysqli? 2021-01-01
- Doctrine 2 - 在多对多关系中记录更改 2022-01-01
- phpmyadmin 错误“#1062 - 密钥 1 的重复条目‘1’" 2022-01-01
- HTTP 与 FTP 上传 2021-01-01
- 在 yii2 中迁移时出现异常“找不到驱动程序" 2022-01-01
- 如何在 Symfony 和 Doctrine 中实现多对多和一对多? 2022-01-01
- 找不到类“AppHttpControllersDB",我也无法使用新模型 2022-01-01
- PHP 守护进程/worker 环境 2022-01-01
- 在 CakePHP 2.0 中使用 Html Helper 时未定义的变量 2021-01-01
- 使用 PDO 转义列名 2021-01-01