我有一个这样的表:
id title parent_id
1 a 0
2 b 0
3 c 1
4 d 2
5 e 1
6 f 3
7 g 3
我需要制作一个 json 发送到前端。我不知道如何从我的表中制作这个 json。 这是有关我的目标和代码的其他一些信息: 节点类型:
type Node struct {
Id int64 `json:"id"'
Title string `json:"title"`
ParentId int64 `json:"parent_id"`
Children []Node `json:"children"`
}
我正在使用 sqlx 从数据库读取到 slice
我需要这样的 json:
[
{
"id" : 1,
"title" : "a",
"parent_id" : 0,
"children" : [
{
"id" : 3,
"title" : "c",
"parent_id" : 1,
"children" .....
}
]
},
.
.
.
]
已经有一个问题类似于我的问题,但不同之处在于我从 mysql 表而不是控制台读取节点,而且我需要将树编码为 json
最佳答案
var items = select * from tbl order by parent_id;
Node.addChild = n=>this.children.add(n);
var root= new Node({Id:0, Parent:null, Title:'Root',Children:[]);
add(root, items, 0,0)
function add(tree,items, depth){
if(depth>100){
throw 'something';
}
var itemsOnThisLevel = items.where(item.parent_id==tree.id)
foreach(var item in itemsOnThisLevel){
var n = new Node(item);
tree.add(n);
add(n, items, depth+1);
}
}
关于algorithm - 如何从mysql表创建树,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53789133/