0

我在“专辑收藏”中有一个简单的专辑列表。我有一个“album”表,其中有一个“album_id”,一个“collection”表,它有一个“collection_id”和一个“album_collection”表,将两者连接在一起,这样我就可以知道哪些专辑属于一个集合。

对于“album_collection”中的每个链接,我还有一个“排序”列来指定应该阅读专辑的顺序。但是我正在反向执行,这样我就可以在 count + 1 处添加,而不必在添加时将所有订单上移 1。

现在,我可以以图形方式任意重新排列这些专辑……现在我也只需在数据库中进行操作即可。这是我在 PHP 中使用 PDO 的工作解决方案,但我可以说这是一种天真的方法,但我想不出另一种方法来做到这一点。我该如何改进呢?

function rearrange_album_in_collection_order($collection_id, $album_id, $old_index, $new_index){

    if($old_index=== $new_index) return "same order so no change";

    $count = get_album_count($collection_id);
    if($count === 0){
        return "empty collection or incorrect id";
    }

    // this is because we're ordering forwards visually
    // but backwards in the database.
    $old = $count - $old_index + 1;
    $new = $count - $new_index + 1;

    $db = getDatabaseConnection();
    if($new_order > $old_order){

        $reorder = "UPDATE collections_albums 
                    SET ordering = ordering + 1 
                    WHERE collection_id=:cid 
                    AND ordering >= :new 
                    AND ordering < :old"; 

        $stmt = $db->prepare($reorder);

        $stmt->bindValue(":cid", $collection_id);
        $stmt->bindvalue(":old", $old);
        $stmt->bindvalue(":new", $new);

        $stmt->execute();

        $set = "UPDATE collections_albums 
                SET ordering=:new
                WHERE collection_id=:cid AND album_id=:aid"; 

        $stmt = $db->prepare($set);
        $stmt->bindvalue(":new", $new);
         $stmt->bindvalue(":aid", $album_id);
        $stmt->bindValue(":cid", $collection_id);

        $stmt->execute();

    } else {
        $reorder = "UPDATE collections_albums 
                    SET ordering= ordering - 1 
                    WHERE collection_id=:cid 
                    AND ordering <= :new 
                    AND ordering > :old"; 

        $stmt = $db->prepare($reorder);

        $stmt->bindValue(":cid", $collection_id);
        $stmt->bindvalue(":old", $old);
        $stmt->bindvalue(":new", $new);

        $stmt->execute();

        $set = "UPDATE collections_albums 
                SET ordering=:new
                WHERE collection_id=:cid AND album_id=:aid"; 

        $stmt = $db->prepare($set);
        $stmt->bindvalue(":new", $new);
         $stmt->bindvalue(":aid", $album_id);
        $stmt->bindValue(":cid", $collection_id);

        $stmt->execute();
    }
}
4

0 回答 0