使用嵌套集模型在sqlite中存储分层数据,我如何将一个类别移动到另一个类别


Using nested set model to store Hierarchical data in sqlite how can I move a category into another category

我正在尝试使用SQLite存储分层数据。经过大量的搜索,我选择使用嵌套集模型而不是邻接表,因为几乎90%的操作将是读取,只有10%的操作将是更新/删除/创建。

我遵循这个例子:http://www.phpro.org/tutorials/Managing-Hierarchical-Data-with-PHP-and-MySQL.html

它可以很好地添加,删除和读取新节点。

但是我没有找到任何解释如何更新树的文章,例如将一个类别移动到另一个类别。

下面是我的数据库结构:

id   name   left_node   right_node
1    name1     1          2

**我没有找到一个地方解释如何更新层次结构,这是我真正需要的。* *

另一个问题是

public function delete_node($pleft, $pright){
$width = $pright-$pleft+1;
$delete_sql = "delete from categories where left_node between $pleft and $pright";
$update_sql1 = "update categories set right_node = right_node-$width where right_node > $pright";
$update_sql2 = "update categories set left_node = left_node-$width where left_node> $pright";
//
$this->db->trans_start();
//
$this->db->query($delete_sql);
//
$this->db->query($update_sql1);
$this->db->query($update_sql2);
$this->db->trans_complete();
//
return $this->db->trans_status();
}

这是我的删除方法,它需要30ms才能完成。这正常吗?

我解决了这个问题,谢谢你的帮助https://rogerkeays.com/how-to-move-a-node-in-nested-sets-with-sql

我正在使用sqlite数据库的编码器。下面是我的函数

public function move_node($pleft, $pright, $origin_left_pos, $origin_right_pos){
//
//the new_left_position is different according to which way you want to move the node 
$new_left_position = $pleft + 1;
//
$width = $origin_right_pos - $origin_left_pos + 1;
$temp_left_position = $origin_left_pos;
$distance = $new_left_position - $origin_left_pos;
//backwards movement must account for new space
if($distance < 0){
  $distance -= $width;
  $temp_left_position += $width;
}
//
$update_sql1 = "update categories set left_node = left_node+$width where left_node >=  $new_left_position";
$update_sql2 = "update categories set right_node = right_node+$width where right_node >= $new_left_position";
//
$update_sql3 = "update categories set left_node = left_node+$distance , right_node = right_node+$distance where left_node >= $temp_left_position AND right_node < $temp_left_position+$width";
//
$update_sql4 = "update categories set left_node = left_node-$width where left_node > $origin_right_pos";
$update_sql5 = "update categories set right_node = right_node-$width where right_node > $origin_right_pos";
//
$this->db->trans_start();
$this->db->query($update_sql1);
//
$this->db->query($update_sql2);
$this->db->query($update_sql3);
$this->db->query($update_sql4);
$this->db->query($update_sql5);
$this->db->trans_complete();
return $this->db->trans_status();
}

关于你的问题有几个答案:

移动嵌套集中的节点

移动嵌套集树中的节点

关于你的delete方法运行的时间,30ms对于这种操作来说是非常少的,所以没有什么可担心的。不要陷入过早优化的陷阱。:)