gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-28 23:26:06 25 4
gpt4 key购买 nike

我有一个包含对象的表,它看起来像这样:

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

关于php - MYSQL/PHP 在保持数字顺序的同时向上或向下移动对象的顺序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39263388/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com