SQLite - 有更好的方法来改变行的相对排序吗?

时间:2013-07-20 16:05:08

标签: php sqlite pdo

我在“专辑集”中有一个简单的专辑列表。我有一个“专辑”表,其中有一个“album_id”,一个“集合”表,其中有一个“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();
    }
}

0 个答案:

没有答案