jeudi 4 août 2016

How to replicate models with nested relations in Laravel

I have a model with a lot of nested relations. I first load them like this:

<?php
$model = Model::where('id', $id)
    ->with(
        'relation1',
        'relation2',
        'relation2.subrelation1', 
        'relation2.subrelation2',
        'relation3', 
        'relation3.subrelation1', 
        'relation3.subrelation2',
        'relation3.subrelation3', 
        'relation3.subrelation4.subrelation', 
    )->get();
?>

And here is how I replicate the relations and eventually clone them.

<?php
$clone = $model->replicate();
$clone->push();

    foreach ($model->getRelations() as $relation => $entries){
        foreach($entries as $entry){
            $e = $entry->replicate();
            if ($e->push()){
                $clone->{$relation}()->save($e);

                // @todo Go further down

            }
        }
    }
?>

The problem is that this works perfectly for relations in the first level; however, if there are additional nested relations, they are not getting replicated/cloned. What is the most efficient way to traverse further in the relations and replicate them all?

Thanks



via Chebli Mohamed

Aucun commentaire:

Enregistrer un commentaire