Jimmery
Jimmery

Reputation: 10119

Replicating multiple models at once

I am using Laravel 4.2.

If I want to duplicate a model I can use the following:

$newModel = $currentModel->replicate();
$newModel->save();

However I have this inside a loop, like so:

foreach ($this->models as $currentModel) {
    $newModel = $currentModel->replicate();
    $newModel->save();
}

Which obviously causes a several DB calls. I want something more efficient, so I can loop through my models and then outside of the loop use one DB call to write them all in one go.

In Laravel is there a way to replicate multiple models in one go?

Upvotes: 0

Views: 709

Answers (2)

Maraboc
Maraboc

Reputation: 11083

You can use the insert statment of DB query builder like this :

foreach ($this->models as $currentModel) {
    $newModel = $currentModel->replicate()
    $newModels[] = $newModel->toArray();
}
DB::table('table_name')->insert($newModels);

Upvotes: 1

LorenzoBerti
LorenzoBerti

Reputation: 6974

No it not possible duplicate more than one model, you can see in the api documentation: https://laravel.com/api/4.2/Illuminate/Database/Eloquent/Model.html#method_replicate

So if you would duplicate X models you need loop them and you can speific (with array parameter) wich columns you would like to not copy

Upvotes: 0

Related Questions