原文鏈接:https://www.zhoubotong.site/post/91.html 通常樹形菜單的實現基本就是遞歸調用,大部分場景畢竟這種數據不多,性能倒是並不突出, 下麵給個demo,有興趣的朋友可以看看: 新建一個city表: CREATE TABLE `city` ( `id` int ...
原文鏈接:https://www.zhoubotong.site/post/91.html
通常樹形菜單的實現基本就是遞歸調用,大部分場景畢竟這種數據不多,性能倒是並不突出, 下麵給個demo,有興趣的朋友可以看看: 新建一個city表:
CREATE TABLE `city` (
`id` int NOT NULL AUTO_INCREMENT,
`pid` int NOT NULL DEFAULT '0' COMMENT '父級別id',
`name` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NOT NULL DEFAULT '0' COMMENT '名稱',
PRIMARY KEY (`id`) USING BTREE,
KEY `pid` (`pid`) USING BTREE
) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_general_ci;
測試數據:
INSERT INTO `city` (`id`, `pid`, `name`) VALUES (1, 0, '廣東省');
INSERT INTO `city` (`id`, `pid`, `name`) VALUES (2, 1, '廣州市');
INSERT INTO `city` (`id`, `pid`, `name`) VALUES (3, 2, '廣州天河區');
INSERT INTO `city` (`id`, `pid`, `name`) VALUES (4, 2, '海珠區');
INSERT INTO `city` (`id`, `pid`, `name`) VALUES (5, 0, '福建省');
INSERT INTO `city` (`id`, `pid`, `name`) VALUES (6, 5, '廈門市');
INSERT INTO `city` (`id`, `pid`, `name`) VALUES (7, 4, '新港');
INSERT INTO `city` (`id`, `pid`, `name`) VALUES (8, 4, '沙園');
INSERT INTO `city` (`id`, `pid`, `name`) VALUES (9, 7, '新港一區');
INSERT INTO `city` (`id`, `pid`, `name`) VALUES (10, 0, '湖北省');
INSERT INTO `city` (`id`, `pid`, `name`) VALUES (11, 10, '武漢市');
INSERT INTO `city` (`id`, `pid`, `name`) VALUES (12, 11, '黃陂區');
INSERT INTO `city` (`id`, `pid`, `name`) VALUES (13, 11, '洪山區');
INSERT INTO `city` (`id`, `pid`, `name`) VALUES (14, 12, '黃陂天河街道');
demo.go:
package main
import (
"encoding/json"
"fmt"
"gorm.io/driver/mysql"
"gorm.io/gorm"
)
var DB gorm.DB
func (u TreeNode) TableName() string {
return "city"
}
type TreeNode struct {
Id int `json:"id"`
Pid int `json:"pid" gorm:"index"`
Name string `json:"name" gorm:"size:255"`
Children []*TreeNode `json:"children" gorm:"-"`
}
func init() {
dsn := "root:uos123456@tcp(11213:3306)/demo?charset=utf8mb4&parseTime=True&loc=Local"
db, err := gorm.Open(mysql.Open(dsn), &gorm.Config{})
if err != nil {
panic("failed to connect database")
}
DB = *db
}
func main() {
data := TreeList(10) // 查詢武漢市下的子節點
str, _ := json.Marshal(data)
fmt.Printf("%s\\n", str)
}
// TreeList 遞歸處理子節點list
func TreeList(pid int) []*TreeNode {
var list []*TreeNode
DB.Model(TreeNode{}).Where("pid= ?", pid).Find(&list)
result := make([]*TreeNode, 0)
for _, v := range list {
if v.Pid == pid {
v.Children = TreeList(v.Id)
if v.Children == nil {
v.Children = make([]*TreeNode, 0)
}
result = append(result, v)
}
}
return result
}
輸出結果:
[Running] go run "/media/uos/G/web/demo-go/demo.go"
[{"id":11,"pid":10,"name":"武漢市","children":[{"id":12,"pid":11,"name":"黃陂區","children":[{"id":14,"pid":12,"name":"黃陂天河街道","children":[]}]},{"id":13,"pid":11,"name":"洪山區","children":[]}]}]
無論從事什麼行業,只要做好兩件事就夠了,一個是你的專業、一個是你的人品,專業決定了你的存在,人品決定了你的人脈,剩下的就是堅持,用善良專業和真誠贏取更多的信任。