Laravel Eloquent ORM replicate

前端 未结 4 1505
悲哀的现实
悲哀的现实 2020-12-18 22:19

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         


        
4条回答
  •  忘掉有多难
    2020-12-18 22:43

    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.

提交回复
热议问题