亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

如何從mysql表創建樹

如何從mysql表創建樹

Go
繁星coding 2023-05-15 15:36:07
我有一張這樣的桌子:id        title        parent_id1         a            02         b            03         c            14         d            25         e            16         f            37         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 回答

?
烙印99

TA貢獻1829條經驗 獲得超13個贊

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

    }

}


查看完整回答
反對 回復 2023-05-15
  • 1 回答
  • 0 關注
  • 154 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號