API
// ListCategoryReq 类目列表请求参数
type ListCategoryReq struct {
g.Meta `path:"/ListCategory" tags:"平台类目模块" method:"post" summary:"类目列表"`
*model.ListCategoryReq
commonApi.Author
}
// ListCategoryRes 类目列表返回结果
type ListCategoryRes struct {
List []*model.ListCategoryRes `json:"list" dc:"集合"`
commonApi.EmptyRes
}
model
type ListCategoryReq struct {
}
type ListCategoryRes struct {
CategoryID int64 `json:"categoryId"` // 类目ID
Image string `json:"image"` // 类目图片
CategoryName string `json:"categoryName"` // 类目名称
Deep string `json:"deep"` // 类目深度
CategorySort int `json:"categorySort"` // 类目排序
ParentID int64 `json:"parentId"` // 父类目ID
Children []*ListCategoryRes `json:"categoryInfoVos"` // 子类目列表
}
logic
// ListCategory 类目列表
func (s *sSysCategory) ListCategory(ctx context.Context, req *system.ListCategoryReq) (res *system.ListCategoryRes, err error) {
err = g.Try(ctx, func(ctx context.Context) {
categoriesResult, err := dao.Category.Ctx(ctx).WithAll().Order("id DESC").All()
if err != nil {
liberr.ErrIsNil(ctx, errors.New("获取类目数据失败"), "获取类目数据失败")
return
}
// 将数据库查询结果转换为 []*model.ListCategoryRes 类型
var categories []*model.ListCategoryRes
for _, result := range categoriesResult {
category := &model.ListCategoryRes{
CategoryID: result["id"].Int64(),
Image: result["image"].String(),
CategoryName: result["category_name"].String(),
Deep: result["deep"].String(),
CategorySort: result["category_sort"].Int(),
ParentID: result["parent_id"].Int64(),
}
categories = append(categories, category)
}
// 构造 ListCategoryRes 对象
res = &system.ListCategoryRes{
List: buildCategoryTree(categories),
}
// 将 categoryInfoVos 为 nil 的项转换为空数组
for _, category := range res.List {
if category.Children == nil {
category.Children = []*model.ListCategoryRes{}
}
}
})
return
}
// buildCategoryTree 根据类目列表构建动态级联关系树
func buildCategoryTree(categories []*model.ListCategoryRes) []*model.ListCategoryRes {
categoryMap := make(map[int64]*model.ListCategoryRes)
var rootCategories []*model.ListCategoryRes
// 构建类目映射
for _, category := range categories {
categoryMap[category.CategoryID] = category
}
// 构建动态级联关系树
for _, category := range categories {
if category.ParentID == 0 {
rootCategories = append(rootCategories, category)
} else {
parent, ok := categoryMap[category.ParentID]
if ok {
// 检查 Children 是否为 nil,如果是则设置为空切片
if parent.Children == nil {
parent.Children = make([]*model.ListCategoryRes, 0)
}
parent.Children = append(parent.Children, category)
}
}
}
// 递归处理子节点
for _, root := range rootCategories {
recursiveSetChildren(root)
}
return rootCategories
}
// recursiveSetChildren 递归设置子节点的 Children 字段为空数组
func recursiveSetChildren(node *model.ListCategoryRes) {
if node.Children == nil {
node.Children = []*model.ListCategoryRes{}
} else {
for _, child := range node.Children {
recursiveSetChildren(child)
}
}
}
[GoFrame]树形结构参考例子
于 2024-02-28 15:47:18 首次发布
本文介绍了如何通过API接口获取和处理类目列表数据,包括ListCategoryReq和ListCategoryRes结构,以及如何利用数据库查询和逻辑构建动态类目树,以展示类目的层级关系。
摘要由CSDN通过智能技术生成