MYSQL/PHP 在保持数字顺序的同时向上或向下移动对象的顺序

MYSQL/PHP Shifting order of objects up or down while maintaining numerical order

我有 table 用来存放对象,它看起来像这样:

CREATE TABLE `post_objects` (
  `id` mediumint(7) NOT NULL AUTO_INCREMENT,
  `post_id` mediumint(7) NOT NULL,
  `object_data` text,
  `object_order` tinyint(1) DEFAULT '0',
  `created` datetime DEFAULT CURRENT_TIMESTAMP,
  PRIMARY KEY (`id`)
) ENGINE=MyISAM AUTO_INCREMENT=1 DEFAULT CHARSET=utf8

object_order列跟踪对象的数字顺序,用于在拉动对象时进行排序。它会根据分配给 post_id 的对象数量来维护 1、2、3、4,无穷无尽。

问题:

从我的 PHP 我希望能够将对象向上或向下移动一个增量。例如,将顺序为 3 的对象移动到 2 的位置,并让剩余的对象重新排序,以便仍然保持 1, 2, 3, 4...

我尝试过的:

当前函数没有给我预期的结果。目前,如果我将最后一个位置向下移动,它不会正确重新编号。这是最新的尝试:

// Shift given object order by one in given direction.
function objectOrderShift ($object_id, $shift_type) {
    $post_id = getParentPostId($object_id);
    $current_object_order_value = getObjectOrderValue($object_id);
    switch ($shift_type) {
        case 'up':
            $new_object_order_value = $current_object_order_value - 1;
            break;
        case 'down':
            $new_object_order_value = $current_object_order_value + 1;
            break;
    }

    // Update new object id to new order value (*THERE WILL BE TWO ENTRIES WITH THE SAME ORDER NUMBER*)
    $sql = "UPDATE post_objects SET object_order = :new_object_order_value WHERE id = :object_id";
    $stmt = db::getInstance()->prepare($sql);
     $stmt->bindParam(':object_id', $object_id, PDO::PARAM_INT);
     $stmt->bindParam(':new_object_order_value', $new_object_order_value, PDO::PARAM_INT);
    $stmt->execute();

    //set starting order value
    $object_order_value = 1;
    // Run select for all objects edit as needed
    $sql = "SELECT id, object_order FROM post_objects WHERE post_id = :post_id ORDER BY object_order ASC";
    $stmt = db::getInstance()->prepare($sql);
     $stmt->bindParam(':post_id', $post_id, PDO::PARAM_INT);
    $stmt->execute();
    $results = $stmt->fetchAll();

    foreach ($results as $row) {
        $flux_object_id = $row['id'];  // holder for other object_id's from SELECT query

        if($flux_object_id == $object_id) {
            // This is the already altered object_id, skip entry and ++ value
            $object_order_value++;
        }
        $sql = "UPDATE post_objects SET object_order = :object_order_value, created = NOW() WHERE id = :flux_object_id";
        $stmt = db::getInstance()->prepare($sql);
         $stmt->bindParam(':flux_object_id', $flux_object_id, PDO::PARAM_INT);
         $stmt->bindParam(':object_order_value', $object_order_value, PDO::PARAM_INT);
        $stmt->execute();
        $object_order_value++;
    }
}

您可以在单个查询中完成。由于您只移动一个位置,因此您只需要更新 2 行:您正在移动的对象,以及按对象顺序在其之前或之后的行。

要向下移动对象:

UPDATE post_objects AS p1
JOIN post_objects AS p2 ON p1.object_order IN (p2.object_order, p2.object_order - 1)
SET p1.object_order = 
    CASE WHEN p1.id = p2.id THEN p1.object_order - 1
         ELSE p1.object_order + 1
    END
WHERE p2.id = :object_id