Clone an Eloquent object including all relationships?

后端 未结 10 694
我寻月下人不归
我寻月下人不归 2020-12-01 01:24

Is there any way to easily clone an Eloquent object, including all of its relationships?

For example, if I had these tables:

users ( id, name, email          


        
10条回答
  •  孤城傲影
    2020-12-01 01:29

    Here is an updated version of the solution from @sabrina-gelbart that will clone all hasMany relationships instead of just the belongsToMany as she posted:

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

提交回复
热议问题