What is the correct way to change more than one data in the database (Order)?

Published 2 months ago by infinitanet

Hello, I have an "order" column, this order is the count to sort my articles in homepage.   If I have 3 articles, I'll add an article as the 3ª item. Should I create a tie similar to this?

Before:

 id 1 | Article example | order 1
 id 2 | Article example | order 2
 id 3 | Article example | order 3

After:

 id 1 | Article example | order 1
 id 2 | Article example | order 2
 id 4 | Article example | order 3
 id 3 | Article example | order 4

Code:

 $toChange = Article::where('order', '>=',3)->get();
 foreach($toChange as $item) {
    $item->update(['order'= $item->order +1]);
 }

This works, but is this really a good practice?

  Thank you!

Best Answer (As Selected By infinitanet)
36864

You can issue a mass update to reduce sql queries, but those updates will not trigger any eloquent events that you might have registered.

If that's not a problem for you,

$toChange = Article::where('order', '>=', 3);
$toChange->increment('order');
36864
36864
2 months ago (26,430 XP)

You can issue a mass update to reduce sql queries, but those updates will not trigger any eloquent events that you might have registered.

If that's not a problem for you,

$toChange = Article::where('order', '>=', 3);
$toChange->increment('order');
infinitanet

Thank u!

sutherland

You can also change your order property to a larger number, so something like 100, 200, 300. When you want to insert a record between two values you just take the average of the two. So in your new example you would set it as 250. Of course if you are constantly adjusting order you'll eventually need to start updating values of neighboring rows, but for occasional inserts it might work. The value also wouldn't be human friendly if you need to display it to users. I've never used this myself so I'm curious if anyone has and how it turned out.

infinitanet

@sutherland I had thought so, but my language is Portuguese.   It would be very confusing for you to understand (Google translate).

  Thanks for the answers.

Please sign in or create an account to participate in this conversation.