Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/mysql/58.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Php 如何使用闭包表MySQL创建树_Php_Mysql_Tree_Transitive Closure Table - Fatal编程技术网

Php 如何使用闭包表MySQL创建树

Php 如何使用闭包表MySQL创建树,php,mysql,tree,transitive-closure-table,Php,Mysql,Tree,Transitive Closure Table,我想使用闭包表创建一个用户层次结构树 用户表: 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,

我想使用闭包表创建一个用户层次结构树

用户表:

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\u树中为每个用户创建一条记录。
有没有办法为现有用户创建树