'Is it necessary to avoid loops for updating models in laravel?

I'm trying to sort multiple records for a model based on a field and store their ranks in DB. Like below:

$instances = Model::orderBy('field')->get();

$rank = 1;
foreach ($instances as $instance) {
    $instance->update([
        'rank' => $rank,
    ]);
    $rank++;
}

I have two questions: 1- Is there any alternative ways to avoid using loop? for example I put the ranks in an array and update the whole records by only one magic method. For example:

$instances = Model::orderBy('field')->get();

$rank = 1;
$ranks_array = array();
foreach ($instances as $instance) {
    array_push($ranks_array, $rank);
    $rank++;
}

$instances->magicMethod($ranks_array);

2- Is it necessary at all to do so? are the loops have heavy effects on the server or not? need to say that the number of records I'm going to update may not exceed 50 at all.



Solution 1:[1]

For insert queries, inserting all records at once will go much faster than inserting them one by one. However for update queries, if you need to update specific rows with specific data, there is no other way than to update them one by one.

Solution 2:[2]

I recently came across a similar issue where I needed to update 90k+ row from my DB. Because I needed to add specific values to each column I needed to individually update each column.

What I found was instead of doing

$DBModel = Model::get();
foreach ($DBModel as $row) {
 $row->notify = $row->paid;
 // the date is calculated from a specific carbon date from another column
 // I did not include the logic here for the example
 $row->due = "0000-00-00 00:00:00";
 $row->save();
}

Running the previous query took 5m33s

But doing it like this

$DBModel = Model::get();
DB::beginTransaction();
foreach ($DBModel as $row) {
 DB::update(update TABLE_NAME set due = ?, notify = ? where id = ?",
     ["0000-00-00 00:00:00", $row->paid, $row->id]
 );
}
DB::commit();

The previous query took only 1m54s to execute.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Jerodev
Solution 2 Pierre