BKWLD / cloner

A trait for Laravel Eloquent models that lets you clone a model and it's relationships, including files. Even to another database.
MIT License
463 stars 55 forks source link

Self Relational Clone #22

Open korki696 opened 5 years ago

korki696 commented 5 years ago

Is there anyway to clone a model that has a self relational field:

id parent_id

If I set up the protected $cloneable_relations property It doubles up on everything. If i keep that off, it doesn't update the parent_id and keeps it the same as the original element.

Any ideas on how to accomplish this?

Thanks

LowSociety commented 5 years ago

If your self-relational models are cloned from another model, try creating an additional relation for just the top-most (where parent_id is null) models and then let the self-relational model clone its children itself:

public function modelParents()
{
  return $this
    ->hasMany(Model::class)
    ->where('parent_id', '=', null);
}

in $clonable_relations instead of referring to the original relation, just clone the parent models: protected $clonable_relations = ['modelParents'];

Then in the Model class, create a relation for the children, and clone those:

protected $clonable_reations = ['children'];

public function children()
{
    return $this->hasMany(__CLASS__, 'parent_id');
}
sts-ryan-holton commented 7 months ago

@LowSociety Experiencing a similar problem but using the same model as a "Tree". Can you check out https://github.com/BKWLD/cloner/issues/59 and see how i might resolve?