kodeine / laravel-meta

Fluent Meta Data for Eloquent Models, as if it is a property on your model
MIT License
400 stars 90 forks source link

Eloquent replicate with meta relationship #99

Closed stefano-vergani closed 2 years ago

stefano-vergani commented 2 years ago

Hi, seems eloquent replicate does not replicate meta relation.. I also eager loaded metas relationship.

        $newModel = $model->load('metas')->replicate();
        // changing newModel parameters with normal ->attribute ....
        $newModel->save();

Expected behavior: model in database is duplicated with some attributes changed and all metas are duplicated too. Actual behavior: model in database is replicated but no meta saved.

siamak2 commented 2 years ago

Hi Laravel meta only uses metas relation once and then cache it into another property. By replicating it this cached property no longer exist and laravel meta fills this cache again from metas relation. According to replicate source code it just sets current relations results to replicated model and naturally all of the metas still have the original model's id and not replicated. This means that existing metas on replicated model belong to the original model. You can do something like this:

$newModel = $model->replicate()->unsetRelation('metas');
$newModel->setMeta( $model->getMeta()->toArray() );