将集合保存在数据库中而不遍历每个元素并且不插入新记录

Saving a collection in the database without iterating over each element and without inserting new records

我只是想在我的应用程序中处理后将集合保存到数据库。

$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);

我觉得这应该是一个非常简单的解决方案的常见做法,但我一直在四处寻找并没有找到任何东西。

根据文档,您可以尝试更新插入:https://laravel.com/docs/8.x/eloquent#upserts