1

我想通过使用闭包表来创建一个用户层次树。

用户表:

CREATE TABLE `user` (
    `id` INT(11) unsigned NOT NULL AUTO_INCREMENT,
    `parent_id` INT(11) unsigned NOT NULL,
    PRIMARY KEY (`id`)
);

INSERT INTO user (id, parent_id) 
    VALUES (1,0), (2,1), (3,1), (4,1), (5,3), (6,5), (7,0), (8,6);

用户树:

CREATE TABLE `user_tree` (
    `ancestor` INT(11) UNSIGNED NOT NULL,
    `descendant` INT(11) UNSIGNED NOT NULL,
    `level` INT DEFAULT 0,
    PRIMARY KEY (`ancestor`, `descendant`),
    FOREIGN KEY (`ancestor`) REFERENCES `user`(`id`),
    FOREIGN KEY (`descendant`) REFERENCES `user`(`id`)

然后我正在尝试创建一棵树:

public function buildTree()
{
    $stmtUser = $this->db->prepare('SELECT id, parent_id FROM user');
    $stmtUser->execute();
    foreach ($stmtUser as $row) {
        $sql = 'INSERT INTO user_tree (ancestor, descendant) 
                SELECT ancestor, :id FROM user_tree 
                WHERE descendant=:parent_id 
                UNION ALL SELECT :id, :id';
        $stmtTree = $this->db->prepare($sql);
        $stmtTree->execute([
            'id' => $row['id'],
            'parent_id' => $row['parent_id']
        ]);
    }
}

但是这种方法只user_tree为每个用户创建一个记录。有没有办法为现有用户创建树?

4

0 回答 0