【发布时间】:2019-06-12 03:13:31
【问题描述】:
我有一个在 Laravel 5.7 之上使用 PHP 编写的项目。我正在使用 Eloquent ORM 与数据库进行交互。
从数据库中提取大量记录后,我需要能够更新它们。
这就是我的尝试。
$records = Record::where('Key','Test')->get();
$values = collecT([
['Id' => 1, 'Col' => 100],
['Id' => 2, 'Col' => 200],
['Id' => 3, 'Col' => 500],
....
]);
foreach($records as $record) {
$newValue = $values->where('Id', $record->id)->first();
if(is_null($newValue)){
continue;
}
$record->ColName = $newValue['Col'];
$record->save();
}
上述代码不会将更新后的值写入数据库。但是,如果我执行以下操作,它会更新
foreach($values as $value) {
$record = Record::where('Key','Test')->where('id', $value['Id'])->first();
if(is_null($record)){
continue;
}
$record->ColName = $value['Col'];
$record->save();
}
虽然上面的代码有效,但我必须为 $values 数组中的每条记录创建 1 个选择 + 1 个更新语句。如果$values 数组的大小为 1000。那将生成多达 2000 个查询,这太疯狂了!
如何在不进行范围更新的情况下正确更新数据库中的多条记录。
【问题讨论】:
标签: php laravel laravel-5 eloquent laravel-5.7