algorithm - 如何从mysql表创建树

标签 algorithm go

我有一个这样的表:

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/

相关文章:

c++ - 寻找混合颜色的起源作为波长

使用 cmd 和 pkg 布局去构建项目 - 构建错误

ubuntu - go 1.13 有 go tools 版本 12.9

algorithm - 如果没有垃圾收集,算法和/或数据结构的一些例子很难或不可能正确实现?

java - 在数百万多边形中找到数千个点的快速算法?

java - 用 PL 写 2^x

arrays - 在 Go 中使用 slice 进行子集检查

go - 使用 "database/sql"时如何防止 Go 中的 SQL 注入(inject)攻击?

go - 使用 Kubernetes go 客户端的部署列表的返回类型

php - PHP 中的数组差异实现