本文介绍了预遍历父子动态插入不起作用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下数据库:

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

我想在上述预定遍历表中插入记录。为此,我使用了以下代码和查询:

I want to insert record in the above preorder traversal table. For that I used the following code and queries:

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。问题是当我尝试插入记录ex时。 Jr.Manager和Sr.Manager在管理器类别下,未正确插入。代替管理器类别,它会插入HR-> Jr.Manager-> Sr.Manager之类。
上面的代码有什么问题?

I am getting lft, rgt and level from database. The problem is when I tried to insert record ex. Jr.Manager and Sr.Manager under Manager category, it is not inserted properly. Instead of "Manager" category its inserting under HR->Jr.Manager->Sr.Manager like. Whats wrong with above code?

下面是更好理解的图像:

Here is the image for better understanding:

推荐答案

我有点修改您的代码,只需尝试以下操作:

I am slightly modified your code just try this:

    $name = $_GET['name'];
    $rgt = $_GET['rgt'];
    $lft = $_GET['lft'];
    $level = $_GET['level'] + 1;
    $right = $rgt + 1;

    $sql1 = "UPDATE xp_subunit SET lft = lft+2 WHERE lft >= $rgt ;";
    $this->db->query($sql1);
    $sql2 = "UPDATE xp_subunit SET rgt = rgt+2 WHERE rgt >= $rgt ;";
    $this->db->query($sql2);
    $sql3 = "INSERT INTO xp_subunit (`id`,`name`,`unit_id`,`lft`, `rgt`, `level`)        
values (NULL, '$name', '$unit_id',$rgt, $right, '$level');";
    echo $this->db->query($sql3);

它将为您工作。

这篇关于预遍历父子动态插入不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-26 19:57