我有以下数据库:
id name unit_id lft rgt level
-- -------------- ------- --- --- -----
1 Company Name 1 1 2 0
2 Manager 2 2 9 1
3 HR 3 3 8 2
4 Jr.Manager 5 5 8 2
5 Sr.Manager 8 7 8 2
我想在上面的前序遍历表中插入记录。为此,我使用了以下代码和查询:
function addstructure() {
$level = $_GET['level'] + 1;
$rgt = $_GET['rgt'] + 1;
if ($_GET['level'] == 0) {
$sql = "UPDATE xp_subunit SET lft = lft+2, rgt=rgt+2 WHERE rgt > " . $_GET['rgt'] . "; ";
$this->db->query($sql);
$sql = "INSERT INTO xp_subunit SET level=" . $level . ", lft =" . $_GET['rgt'] . ", rgt = " . $rgt . " , name = '" . $_GET['name'] . "', unit_id='" . $_GET['unit_id'] . "', description='" . $_GET['description'] . "';";
$this->db->query($sql);
} else {
$sql = "UPDATE xp_subunit SET rgt = rgt+2 WHERE rgt > " . $_GET['lft'] . "; ";
$this->db->query($sql);
$sql = "INSERT INTO xp_subunit SET level=" . $level . ", lft =" . $_GET['rgt'] . ", rgt = " . $rgt . " , name = '" . $_GET['name'] . "', unit_id='" . $_GET['unit_id'] . "', description='" . $_GET['description'] . "';";
echo $this->db->query($sql);
}
}
我正在从数据库中获取 lft、rgt 和 level。问题是当我尝试插入记录前。Manager 类别下的 Jr.Manager 和 Sr.Manager 未正确插入。而不是“经理”类别,而是在 HR->Jr.Manager->Sr.Manager 下插入。上面的代码有什么问题?
这是更好理解的图像: