【发布时间】:2015-06-08 09:20:32
【问题描述】:
我正在尝试使用 SQLite 存储分层数据。经过大量搜索,我选择使用nested set model 而不是adjacency list,因为几乎 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();
}
这是我的删除方法,需要 30 毫秒才能完成。这正常吗?
我已经解决了,谢谢你的帮助 https://rogerkeays.com/how-to-move-a-node-in-nested-sets-with-sql
我正在使用带有 sqlite 数据库的 codeigniter。 以下是我的功能,
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();
}
【问题讨论】:
标签: php database sqlite hierarchical