如何使用 laravel 更新数据库中的多个记录值?

How to update multiple records value in database using laravel?

最初,students table 如下所示。

id | invite_count
-----------------
10 | 5
12 | 0
15 | 1
25 | 0

我正在使用以下代码更新学生的邀请数。

Student::whereIn("id", $this->request->studentIds)
        ->update([
            'invite_count' => DB::raw('invite_count+1')
        ]);

但根据我的要求,我可以在 $this->request->studentIds 数组中多次使用相同的 ID,例如 [10, 15, 12, 10, 25, 12]。

运动时,输出如下所示。

id | invite_count
-----------------
10 | 6
12 | 1
15 | 2
25 | 1

但我想要如下输出。

id | invite_count
-----------------
10 | 7
12 | 2
15 | 2
25 | 1

如何存档?

一种方法是使用 chunkById 进行块查询。要进行更新,请确保 invite_count 列可在模型

中填写
$ids=[10, 15, 12, 10, 25, 12];

$groupByIds=array_count_values($ids);


Student::whereIn("id",array_keys($groupByIds))
        ->chunkById(50, function ($students)use($groupByIds) {
            $students->each(function ($student, $key)use($groupByIds) {
                $student->update(['invite_count' => $student->invite_count+($groupByIds[ $student->id])]);
            });

        }, $column = 'id');

 Student::whereIn("id",array_keys($groupByIds))
            ->chunkById(50, function ($students)use($groupByIds) {
                $students->each(function ($student, $key)use($groupByIds) {
                    $student->invite_count=$student->invite_count+$groupByIds[ $student->id]);
$student->save();
                });

        }, $column = 'id');

参考:https://laravel.com/docs/8.x/eloquent#chunking-results