Home > Software engineering >  Saving a collection in the database without iterating over each element and without inserting new re
Saving a collection in the database without iterating over each element and without inserting new re

Time:01-05

I simply want to save a collection to the database after processing it in my application.

$data = SomeModel::all();
$data = DataProcessor::process($data);

//Now I want to save the result back to the database...

//This doesn't work since it's a collection so you get the error: 
//"Method Illuminate\Database\Eloquent\Collection::save does not exist."

$data ->save();

//This works but is not feasible due to the amount (thousands) of records needed to be updated

foreach($data as $dat){
    $dat->save();
}

//This doesn't work because I'm updating, not inserting new records. 
//So I get integrity constraint violation on id

SomeModel::insert($data);

I feel this should be a common practice with a pretty straightforward solution but I've been looking around and haven't found anything.

CodePudding user response:

According docs, you could try upserts: https://laravel.com/docs/8.x/eloquent#upserts

  •  Tags:  
  • Related