Clone an Eloquent object including all relationships?

后端 未结 10 687
我寻月下人不归
我寻月下人不归 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:56

    tested in laravel 4.2 for belongsToMany relationships

    if you're in the model:

        //copy attributes
        $new = $this->replicate();
    
        //save model before you recreate relations (so it has an id)
        $new->push();
    
        //reset relations on EXISTING MODEL (this way you can control which ones will be loaded
        $this->relations = [];
    
        //load relations on EXISTING MODEL
        $this->load('relation1','relation2');
    
        //re-sync everything
        foreach ($this->relations as $relationName => $values){
            $new->{$relationName}()->sync($values);
        }
    

提交回复
热议问题