Home > Back-end >  How to update multiple records value in database using laravel?
How to update multiple records value in database using laravel?

Time:12-15

Initially, students table looks like below.

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

I am using the below code to update the invite count for students.

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

But according to my requirement, I can have the same id more than one time in the $this->request->studentIds array like [10, 15, 12, 10, 25, 12].

At the movement, the output looks like below.

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

But I want output like below.

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

How can I archive?

CodePudding user response:

One way is using chunk query using chunkById.To work update make sure to invite_count column fillable in model

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

or

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

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

  • Related