这是一个特征,它将以递归方式复制对象上所有已加载的关系。您可以轻松地将此扩展为其他关系类型,例如Sabrina的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});
}
}
}
用法:
$new = $this->replicate();
$new->push();
$this->relations = [];
$this->load('relation1','relation2.nested_relation');
self::duplicateRelations($this, $new);