如何从MySQL表制作树

时间:2018-12-15 02:51:15

标签: 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从数据库读取数据到切片

我需要一个像这样的json:

[
    {
    "id" : 1,
    "title" : "a",
    "parent_id" : 0,
    "children" : [ 
                    {
                    "id" : 3,
                    "title" : "c",
                    "parent_id" : 1,
                    "children" .....
                    } 
                 ]
    },    
    .
    .
    .
]

已经有一个与我的问题类似的问题,但是不同之处在于,我是从mysql表而不是从控制台中读取节点,并且还需要将树编组为json

1 个答案:

答案 0 :(得分:0)

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);
    }
}
相关问题