我试图从未知深度的数据库中获取类别列表。是否可以使用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: []}
]
答案 0 :(得分:0)
You should just store every member in the base level in the map and then have a list of all of it's children.
You can then use the map in the same way you would use the array 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
}
It's not exactly clear what you want to do but this will put all of the parents in the entry "0" of the map eliminating the need for a recursive data structure to store all of your categories.
答案 1 :(得分:0)
我找到了解决方案!我在Category struct中添加了一些类别,并从[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))
}