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

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 乌班图ip地址配置及远程SSH
  • ¥15 怎么让点阵屏显示静态爱心,用keiluVision5写出让点阵屏显示静态爱心的代码,越快越好
  • ¥15 PSPICE制作一个加法器
  • ¥15 javaweb项目无法正常跳转
  • ¥15 VMBox虚拟机无法访问
  • ¥15 skd显示找不到头文件
  • ¥15 机器视觉中图片中长度与真实长度的关系
  • ¥15 fastreport table 怎么只让每页的最下面和最顶部有横线
  • ¥15 R语言卸载之后无法重装,显示电脑存在下载某些较大二进制文件行为,怎么办
  • ¥15 java 的protected权限 ,问题在注释里