如何根据数据库中的优先级存储数据?

时间:2014-04-27 21:39:52

标签: php codeigniter

我想将我的类别列表存储在具有优先级的数据库中......比如

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

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

1 个答案:

答案 0 :(得分:0)

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

//$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'); 

没有测试过。希望它有所帮助。