登录
首页 >  Golang >  Go问答

在MySQL中创建层次结构数据

来源:stackoverflow

时间:2024-02-29 21:15:27 243浏览 收藏

小伙伴们有没有觉得学习Golang很有意思?有意思就对了!今天就给大家带来《在MySQL中创建层次结构数据》,以下内容将会涉及到,若是在学习中对其中部分知识点有疑问,或许看了本文就能帮到你!

问题内容

我有一个这样的表:

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


解决方案


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);
    }
}

本篇关于《在MySQL中创建层次结构数据》的介绍就到此结束啦,但是学无止境,想要了解学习更多关于Golang的相关知识,请关注golang学习网公众号!

声明:本文转载于:stackoverflow 如有侵犯,请联系study_golang@163.com删除
相关阅读
更多>
最新阅读
更多>
课程推荐
更多>