如何在数据库中按优先级存储数据


How to store data according to priority in database?

我想将我的类别列表优先存储在数据库中。。。像

cat_id   cat_name   cat_priority
---------------------------------
 1        Test1         1
 2        Test2         2
 3        Test3         3
 4        Test4         4

现在,如果我必须将Test1优先级设置为3。。那么Test3上会有冲突。现在,再次如果我想将Test2优先级设置为4,那么我如何根据优先级系统通过php获取数据。。它将如何工作,以及我需要在表结构中更改什么。。

每次您想要更改项目优先级时,都必须为每个项目重新分配优先级。我想你不想要重复的优先级。

//$category = ...
//get all categories
$categories = $this->db->order_by('cat_priority')->select('cat_id, cat_priority')->get();
$cat_to_change = $category['cat_id'];
$new_priority = 2;
$i_priority = 0;
$new_categories = array();
foreach($categories->result_array() as $row)
{
    //this is the category we want to change, so change it
    if($row['cat_id'] == $cat_to_change)
    {
        $row['cat_priority'] = $new_priority;
    }
    else
    {
        //increment the priority
        $i_priority++;
        //the new priority is owned by another cat
        //so let it for the cat we want for him
        if($row['cat_priority'] == $new_priority)
            $i_priority++;
        $row['cat_priority'] = $i_priority;
    }
    $new_categories[] = $row;
}
//save
$this->db->update_batch('categories', $new_categories, 'cat_id'); 

没有测试。希望有帮助。