我试图从数据库中获得未知深度的类别列表。有可能使用map[int][]interface{}
吗?有可能吗?
type Category struct {
ID int
Name string
ParentID int
}
func GetCategories(db *gorm.DB) map[int][]interface{} {
var result = make(map[int][]interface{})
var categories = []Category{}
db.Where("parent_id = ?", 0).Find(&categories)
for len(categories) > 0 {
var ids []int
for _, cat := range categories {
ids = append(ids, cat.ID)
if cat.ParentID == 0 {
result[cat.ID] = append(result[cat.ID], cat)
} else {
// This work only for 2nd level ...
result[cat.ParentID] = append(result[cat.ParentID], cat)
}
}
}
return result
}
最好的输出是JSON数组。例如:
[
{id: 1, name: "Car", Parent: 0, Children: []},
{id: 2, name: "Boat", Parent: 0, Children: [
{id: 4, name: "Fast", Parent: 2, Children: []},
{id: 5, name: "Slow", Parent: 2, Children: [
{id: 6, name: "ExtraSlow", Parent: 5, Children: []},
]},
]},
{id: 3, name: "Rocket", Parent: 0, Children: []}
]
我找到解决方案了!我在Category结构体中添加了类别切片,并从存储在[depth][]Categories{}
中的数据库中请求每层深度。最后从下到上对所有数据进行排序。
type Category struct {
ID int
Name string
ParentID int
Children []Category
}
func GetCategories(db *gorm.DB) []Category {
// Request data from database
var categories = []Category{}
var store = [][]Category{}
db.Where("parent_id = ?", 0).Find(&categories)
for len(categories) > 0 {
var ids []int
for _, cat := range categories {
ids = append(ids, cat.ID)
}
store = append(store, categories)
categories = []Category{}
db.Where("parent_id in (?)", ids).Find(&categories)
}
// Sort and move children to parent
lastLayer := len(store) - 1
for lastLayer >= 0 {
if (lastLayer - 1 >= 0) {
for _, child := range store[lastLayer] {
for i, parent := range store[lastLayer -1] {
if parent.ID == child.ParentID {
store[lastLayer -1][i].Children = append(store[lastLayer -1][i].
Children, child)
}
}
}
}
lastLayer--;
}
return store[0]
}
// Return content as JSON response in WebApp
func Output(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json")
json.NewEncoder(w).Encode(GetCategories(databaseConnection))
}
你应该把每个成员都存储在map的基层中,然后有一个它的所有子元素的列表。
你可以像使用数组ids
一样使用映射。
func GetCategories(db *gorm.DB) map[int][]interface{} {
var result = make(map[int][]interface{})
var categories = []Category{}
db.Where("parent_id = ?", 0).Find(&categories)
if len(categories) > 0 {
for _, cat := range categories {
if _, ok := result[cat.ID]; !ok {
result[cat.ID] = make([]interface{}, 0, 5)
}
if cat.ParentID != 0 {
if _, ok := result[cat.ParentID]; !ok {
result[cat.ParentID] = make([] interface{}, 0, 5)
}
result[cat.ParentID] = append(result[cat.ParentID], cat)
}
}
}
return result
}
这并不完全清楚你想做什么,但这将把所有的父元素在映射的"0"条目中,消除了递归数据结构来存储所有类别的需要。