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