当前位置:   article > 正文

Go 语言返回组装数据

Go 语言返回组装数据

 

  1. 文章id
  2. 文章标题
  3. .....
  4. 分类 字段 :[
  5. 分类名
  6. ,分类描述
  7. ....
  8. ]
  9. 标签字段 :
  10. [
  11. 标签名,
  12. 标签id
  13. .....
  14. ]
  15. type ArticleWithCategoryLabel struct {
  16. system.SysArticle
  17. CategoryName system.SysCategorie `json:"category_name"`
  18. LabelName system.SysLabel `json:"label_name"`
  19. }
  20. // 文章
  21. func ListSortArticle(c *gin.Context) {
  22. //查询所有的文章
  23. var articles []system.SysArticle
  24. if err := global.GVA_DB.Find(&articles).Error; err != nil {
  25. response.FailWithMessage("获取文章数据失败", c)
  26. return
  27. }
  28. // 查询所有分类
  29. var categories []system.SysCategorie
  30. if err := global.GVA_DB.Find(&categories).Error; err != nil {
  31. response.FailWithMessage("获取分类数据失败", c)
  32. return
  33. }
  34. // 查询所有标签
  35. var labels []system.SysLabel
  36. if err := global.GVA_DB.Find(&labels).Error; err != nil {
  37. response.FailWithMessage("获取标签数据失败", c)
  38. return
  39. }
  40. // 构建分类和标签的映射 将所有的分类 , 标签 放到 Map 中
  41. categoryMap := make(map[int64]system.SysCategorie)
  42. labelMap := make(map[int64]system.SysLabel)
  43. for _, category := range categories {
  44. categoryMap[int64(category.ID)] = category
  45. }
  46. for _, label := range labels {
  47. labelMap[int64(label.ID)] = label
  48. }
  49. // 为每篇文章添加分类名称和标签名称
  50. var articlesWithDetails []ArticleWithCategoryLabel
  51. for _, article := range articles {
  52. // 获取分类名称 筛选出每篇文章对应的分类
  53. category, ok := categoryMap[article.SortID]
  54. if !ok {
  55. continue // 如果找不到分类,跳过这篇文章
  56. }
  57. // 获取标签名称 筛选出每篇文章对应的分类
  58. label, ok := labelMap[article.LabelID]
  59. if !ok {
  60. continue // 如果找不到标签,跳过这篇文章
  61. }
  62. // 添加到结果列表
  63. articlesWithDetails = append(articlesWithDetails, ArticleWithCategoryLabel{
  64. SysArticle: article,
  65. CategoryName: category, 注意定义的是结构体 返回的文章的分类只有一个 多个使用切片
  66. LabelName: label,
  67. })
  68. }
  69. // 准备最终的响应数据 定义一个切片
  70. var finalResponse map[int64][]ArticleWithCategoryLabel = make(map[int64][]ArticleWithCategoryLabel)
  71. for _, articleDetail := range articlesWithDetails {
  72. // 检查 finalResponse 中是否存在 articleDetail.SortID 的条目
  73. if _, exists := finalResponse[articleDetail.SortID]; !exists {
  74. // 如果不存在,初始化一个空切片 相当于php 数组的键 index
  75. finalResponse[articleDetail.SortID] = []ArticleWithCategoryLabel{}
  76. }
  77. // 添加 articleDetail 到对应的切片中 相当于php 的值 value
  78. finalResponse[articleDetail.SortID] = append(finalResponse[articleDetail.SortID], articleDetail)
  79. }
  80. // 返回成功响应
  81. response.OkWithDetailed(finalResponse, "获取数据成功", c)
  82. }

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/寸_铁/article/detail/844307
推荐阅读
相关标签
  

闽ICP备14008679号