Laravel雄辩的ORM复制 [英] Laravel Eloquent ORM replicate

查看:259
本文介绍了Laravel雄辩的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_options
  • 产品属于ToMany类别(通过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());
    }
}

从此处回答:克隆包括所有关系的雄辩的对象?

这个答案(同样的问题),也很好用.

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

从此处:克隆包括所有关系的雄辩的对象吗?

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

The code works fine for many to many relationships in my experience.

这篇关于Laravel雄辩的ORM复制的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆