我认为你已经做对了:
UPDATE items SET order_id = 0 WHERE order_id = 4;
UPDATE items SET order_id = order_id + 1 WHERE order_id >= 1 AND order_id < 4;
UPDATE items SET order_id = 1 WHERE order_id = 0;
要将带有 order_id i 的项目移动到位置 j (i > j):
UPDATE items SET order_id = 0 WHERE order_id = i;
UPDATE items SET order_id = order_id + 1 WHERE order_id >= j AND order_id < i;
UPDATE items SET order_id = j WHERE order_id = 0;
要将带有 order_id i 的项目向下移动到位置 j (j > i):
UPDATE items SET order_id = 0 WHERE order_id = i;
UPDATE items SET order_id = order_id - 1 WHERE order_id > i AND order_id <= j;
UPDATE items SET order_id = j WHERE order_id = 0;
另一种选择是添加一个previous_sibling
. 假设您已经加载了列表,因此您知道之前的兄弟姐妹是[1 => null, 2 => 1, 3 => 2, 4 => 3, 5 => 4]
:
UPDATE items SET previous_sibling = 3 WHERE id = 5; #previous_sibling of 4
UPDATE items SET previous_sibling = null WHERE id = 4; # previous_sibling of 1
UPDATE items SET previous_sibling = 4 WHERE id = 1;