Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

Eluknow's avatar

Define an order and reindex it in MySQL

Hello ! I've got a problem and I really don't know how to solve it. I have a table containing a "order" column. This column isn't like the "id" auto-increment column. Indeed, this column is used for the SQL request (with query builders) : we take the table's datas ordered by the "order" column. And the order is updatable. And I would like it : if somebody updates the "order" of a data, all the others datas have to change their. For example : A data has got as "order" : 3 And a member updates it : 3 -> 4 The data that had the value "4" as "order" updates it as "5", those after as "6" etc. So, the previous value + 1. Do you understand ? I don't know if I am understandable :p. So, is someone able to help me ? How could I do it ? It's a reindexation in db.

0 likes
2 replies
nickywest's avatar
Level 3

When someone moves an item you have to adjust all the items between that item and where it was moved to. So for example lets say you have 4 items where they have sort values:

a: 1
b: 2
c: 3
d: 4

When a user moves "d" to the first position you need to get all the items between the current and destination position (inclusive of the destination) and then increment their display_order. So a PHP side solution would look like this:

$myModel->where('display_order', '=', '4')->first();
$result = $myModel->where('display_order', '<', '4')->where('display_order', '>=', '1')->get();
foreach($result as $ModelObject)
{
    $ModelObject->display_order++;
    $ModelObject->save();
}
$myModel->display_order = 1;
$myModel->save();

If reordering is done frequently, this isn't the most optimized way to handle it since it's making N number of queries where N is the number of elements being shifted. If it's not a common use case, it's probably fine to keep it like that, but in a case where this is a common task I'd do a custom query something like this, where it's all handled by the DB with a single query:

UPDATE my_table SET display_order =
CASE 
    WHEN display_order = 4 THEN 1 
    ELSE display_order + 1 
END 
WHERE display_order BETWEEN 1 AND 4;
1 like
Eluknow's avatar

Okay, I've understood. It works. Thanks a lot, you're my sun for this rainy day :D

Please or to participate in this conversation.