【问题标题】:How to updated multiple records with Laravel and Eloquent?如何使用 Laravel 和 Eloquent 更新多条记录?
【发布时间】: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


    【解决方案1】:

    如果您尝试更新的所有行都将获得相同的值,这是一个简单的问题。问题变得有点棘手,因为您的所有行都需要使用不同的值进行更新。 This comment 在 laravel 的一个 github 问题上有一个解决方案,它可以通过单个查询来完成,在这种情况下,与逐个更新相比,更新 1000 行的性能提高了 13 倍:

    public static function updateValues(array $values)
    {
        $table = MyModel::getModel()->getTable();
    
        $cases = [];
        $ids = [];
        $params = [];
    
        foreach ($values as $id => $value) {
            $id = (int) $id;
            $cases[] = "WHEN {$id} then ?";
            $params[] = $value;
            $ids[] = $id;
        }
    
        $ids = implode(',', $ids);
        $cases = implode(' ', $cases);
        $params[] = Carbon::now();
    
        return \DB::update("UPDATE `{$table}` SET `value` = CASE `id` {$cases} END, `updated_at` = ? WHERE `id` in ({$ids})", $params);
    }
    

    你也可以试试https://github.com/mavinoo/laravelBatch 做类似的事情。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-05-04
      • 2020-11-13
      • 2015-12-05
      • 1970-01-01
      • 1970-01-01
      • 2022-08-09
      相关资源
      最近更新 更多