赞
踩
- 文章id
- 文章标题
- .....
- 分类 字段 :[
- 分类名
- ,分类描述
- ....
- ]
-
- 标签字段 :
- [
- 标签名,
- 标签id
- .....
- ]
-
-
-
-
- type ArticleWithCategoryLabel struct {
- system.SysArticle
- CategoryName system.SysCategorie `json:"category_name"`
- LabelName system.SysLabel `json:"label_name"`
- }
-
-
-
-
-
- // 文章
- func ListSortArticle(c *gin.Context) {
-
- //查询所有的文章
- var articles []system.SysArticle
- if err := global.GVA_DB.Find(&articles).Error; err != nil {
- response.FailWithMessage("获取文章数据失败", c)
- return
- }
-
- // 查询所有分类
- var categories []system.SysCategorie
- if err := global.GVA_DB.Find(&categories).Error; err != nil {
- response.FailWithMessage("获取分类数据失败", c)
- return
- }
-
- // 查询所有标签
- var labels []system.SysLabel
- if err := global.GVA_DB.Find(&labels).Error; err != nil {
- response.FailWithMessage("获取标签数据失败", c)
- return
- }
-
- // 构建分类和标签的映射 将所有的分类 , 标签 放到 Map 中
- categoryMap := make(map[int64]system.SysCategorie)
- labelMap := make(map[int64]system.SysLabel)
- for _, category := range categories {
- categoryMap[int64(category.ID)] = category
- }
- for _, label := range labels {
- labelMap[int64(label.ID)] = label
- }
-
-
-
-
-
- // 为每篇文章添加分类名称和标签名称
- var articlesWithDetails []ArticleWithCategoryLabel
- for _, article := range articles {
- // 获取分类名称 筛选出每篇文章对应的分类
- category, ok := categoryMap[article.SortID]
- if !ok {
- continue // 如果找不到分类,跳过这篇文章
- }
-
- // 获取标签名称 筛选出每篇文章对应的分类
- label, ok := labelMap[article.LabelID]
- if !ok {
- continue // 如果找不到标签,跳过这篇文章
- }
-
- // 添加到结果列表
- articlesWithDetails = append(articlesWithDetails, ArticleWithCategoryLabel{
- SysArticle: article,
- CategoryName: category, 注意定义的是结构体 返回的文章的分类只有一个 多个使用切片
- LabelName: label,
- })
- }
-
- // 准备最终的响应数据 定义一个切片
- var finalResponse map[int64][]ArticleWithCategoryLabel = make(map[int64][]ArticleWithCategoryLabel)
- for _, articleDetail := range articlesWithDetails {
- // 检查 finalResponse 中是否存在 articleDetail.SortID 的条目
- if _, exists := finalResponse[articleDetail.SortID]; !exists {
- // 如果不存在,初始化一个空切片 相当于php 数组的键 index
- finalResponse[articleDetail.SortID] = []ArticleWithCategoryLabel{}
- }
- // 添加 articleDetail 到对应的切片中 相当于php 的值 value
- finalResponse[articleDetail.SortID] = append(finalResponse[articleDetail.SortID], articleDetail)
- }
-
- // 返回成功响应
- response.OkWithDetailed(finalResponse, "获取数据成功", c)
-
- }

Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。