douqi3064 2016-03-15 20:14
浏览 278
已采纳

Laravel Eloquent ORM复制

I have a problem with replicating one of my models with all the relationships.

The database structure is as follows:

Table1: products
id
name

Table2: product_options
id
product_id
option

Table3: categories
id
name

Pivot table: product_categories
product_id
category_id

Relationships are:

  • product hasMany product_options
  • product belongsToMany category (trough 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();
}

But this does not works (the relationships are not cloned - currently I just tried to clone the product_options).

  • 写回答

4条回答 默认 最新

  • douxin8383 2016-03-16 09:38
    关注

    This code, worked for me:

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

    Answer from here: Clone an Eloquent object including all relationships?

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

    From here: Clone an Eloquent object including all relationships?

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

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(3条)

报告相同问题?

悬赏问题

  • ¥15 求差集那个函数有问题,有无佬可以解决
  • ¥15 【提问】基于Invest的水源涵养
  • ¥20 微信网友居然可以通过vx号找到我绑的手机号
  • ¥15 寻一个支付宝扫码远程授权登录的软件助手app
  • ¥15 解riccati方程组
  • ¥15 display:none;样式在嵌套结构中的已设置了display样式的元素上不起作用?
  • ¥15 使用rabbitMQ 消息队列作为url源进行多线程爬取时,总有几个url没有处理的问题。
  • ¥15 Ubuntu在安装序列比对软件STAR时出现报错如何解决
  • ¥50 树莓派安卓APK系统签名
  • ¥65 汇编语言除法溢出问题