[GoFrame]树形结构参考例子

本文介绍了如何通过API接口获取和处理类目列表数据,包括ListCategoryReq和ListCategoryRes结构,以及如何利用数据库查询和逻辑构建动态类目树,以展示类目的层级关系。
摘要由CSDN通过智能技术生成
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)
		}
	}
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

淡忘_cx

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值