Clone an Eloquent object including all relationships?

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

    Here is a trait that will recursively duplicate all the loaded relationships on an object. You could easily expand this for other relationship types like Sabrina's example for belongsToMany.

    trait DuplicateRelations
    {
        public static function duplicateRelations($from, $to)
        {
            foreach ($from->relations as $relationName => $object){
                if($object !== null) {
                    if ($object instanceof Collection) {
                        foreach ($object as $relation) {
                            self::replication($relationName, $relation, $to);
                        }
                    } else {
                        self::replication($relationName, $object, $to);
                    }
                }
            }
        }
    
        private static function replication($name, $relation, $to)
        {
            $newRelation = $relation->replicate();
            $to->{$name}()->create($newRelation->toArray());
            if($relation->relations !== null) {
                self::duplicateRelations($relation, $to->{$name});
            }
        }
    }
    

    Usage:

    //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.nested_relation');
    
    // duplication all LOADED relations including nested.
    self::duplicateRelations($this, $new);
    

提交回复
热议问题