目标数据结构:
[{
"k1": "v",
"k2": [{
"k1": "v1",
"k2": []
}]
}]
三级菜单,有3层数组,即3个[],第一层数组存储一级菜单,第二个数组存储对应一个一级菜单的二级菜单,第三个数组存储对应一个二级菜单的三级菜单。
以下代码的测试数据:链接:https://pan.baidu.com/s/1ITpnjhrrt0G_XPuOS_TQ0w
提取码:homx
package main
import (
"github.com/astaxie/beego/orm"
)
type TpshopCategory struct {
Id int
CateName string `orm:"default('')"`
Pid int `orm:"default(0)"`
IsShow int `orm:"default(1)"`
CreateTime int `orm:"null"`
UpdateTime int `orm:"null"`
DeleteTime int `orm:"null"`
}
func init() {
//注册数据库
orm.RegisterDataBase("default","mysql","root:123456@tcp(192.168.160.140:3306)/yzdb")
//注册表结构
orm.RegisterModel(new(TpshopCategory))
//建表
orm.RunSyncdb("default",false,true)
}
func main(){
var (
sliceTypes []map[string]interface{} //mapItem
sliceResultsCond []TpshopCategory//查询条件:pid=0
//range sliceResultsCond: begin
mapItem map[string]interface{} //k1:一级菜单TpshopCategory, k2:sliceMapItem2
sliceResultsCond2 []TpshopCategory//查询条件:pid= mapItem.k1.value.id
//range sliceResultsCond2: begin
sliceMapItem2 []map[string]interface{} //k3:是二级菜单TpshopCategory, k4:sliceResultsCond3
mapItem2 map[string]interface{}
sliceResultsCond3 []TpshopCategory //查询条件是 pid=mapItem2.k1.value.id
//range sliceResultsCond2: end
//range sliceResultsCond: end
)
sliceTypes = make([]map[string]interface{},0)
o := orm.NewOrm()
o.QueryTable("TpshopCategory").Filter("Pid", 0).All(&sliceResultsCond)
for _, v := range sliceResultsCond {
mapItem = make(map[string]interface{})
mapItem["k1"] = v
o.QueryTable("TpshopCategory").Filter("Pid", v.Id).All(&sliceResultsCond2)
for _, v2 := range sliceResultsCond2 {
sliceMapItem2 = make([]map[string]interface{},0)
mapItem2 = make(map[string]interface{})
mapItem2["k1"] = v2
o.QueryTable("TpshopCategory").Filter("Pid", v2.Id).All(&sliceResultsCond3)
mapItem2["k2"] = sliceResultsCond3
sliceMapItem2 = append(sliceMapItem2, mapItem2)
mapItem["k2"] = sliceMapItem2
}
sliceTypes = append(sliceTypes, mapItem)
}
}