The guys at the top want sort order to be customizable in our app. So I have a table that effectively defines the data type. What is the best way to store our sort order. If
The basic algorithm might be like one described below. Initially the sort field varies from item to item by 1000 (you may consider another interval). The items in the table are in ordered state just for the sake of simplicity. Btw, I've create Yii2 component to manage this stuff. And this one if you need a sortable tree sortable tree.
id | sort
---+-----
1 | 1000
---+-----
2 | 2000
---+-----
3 | 3000
---+-----
Lets imagine we are going to add an item (id 4) after id 1:
id | sort
---+-----
1 | 1000
---+-----
4 | 1500
---+-----
2 | 2000
---+-----
3 | 3000
---+-----
So to calculate sort value for id 4 we took the sort value of the item before, which is 1000 and the item after - 2000 and took the mean. If you get a float, just round it to the nearest integer. If you need to insert an item at the beginning of the list, then you take a mean of (1000 and 0, which is 500).
Now, if we need to insert an item (id 5) after id 1, we do the same:
id | sort
---+-----
1 | 1000
---+-----
5 | 1250
---+-----
4 | 1500
---+-----
2 | 2000
---+-----
3 | 3000
---+-----
Later on, you might face to this scenario:
id | sort
---+-----
1 | 1000
---+-----
15 | 1001
---+-----
...
---+-----
5 | 1250
---+-----
...
---+-----
So if you need to insert an item (id 16) between 1 and 15, first you should increment sort field by 1000 of all items followed by 1:
id | sort
---+-----
1 | 1000
---+-----
15 | 2001
---+-----
...
---+-----
5 | 2250
---+-----
...
---+-----
Now you can insert the item (id 16):
id | sort
---+-----
1 | 1000
---+-----
16 | 1501
---+-----
15 | 2001
---+-----
...
---+-----
5 | 2250
---+-----
...
---+-----