Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Laravel 5.2 - Updating multiple rows with one query

Tags:

php

mysql

laravel

So I do a lot of calculations and at the end I have rates that need to be saved to existing rows in a table.

The array I have will be similar to the following:

[
    <model_id> => [
        'rate' => <some rate>
    ]
    <model_id_2> => [
        'rate' => <some other rate>
    ]
    .....
]

Now obviously I could foreach through this array and do an update for each and every item in the array but I could end up with 100 update calls. Is there a way (through laravel's eloquent OR even a raw sql query) to do all these updates through one call?

like image 502
Bill Garrison Avatar asked Jan 19 '16 19:01

Bill Garrison


2 Answers

You may try with Eloquent update() for multiple records update. Here is some code which I am using for update multiple records into the my table.

\App\Notification::where('to_id', '=', 0)
                ->update(['is_read' => 1]); 
like image 107
Nikunj K. Avatar answered Oct 13 '22 20:10

Nikunj K.


If you are worried about the request spent time you can handle this by firing an event and then queueing your listener/job, who will save your model, so it can be processed asynchronously. For examples, go to Laravel Docs for Queues

As long as I know you cannot update multiple rows on Laravel.

like image 26
subzeta Avatar answered Oct 13 '22 20:10

subzeta