music.go 1.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455
  1. package daytask
  2. import (
  3. "app/commons/model/entity"
  4. "github.com/gin-gonic/gin"
  5. )
  6. // MusicGroups 获取歌单列表(含歌曲)
  7. func (s *Server) MusicGroups(c *gin.Context) {
  8. ctx := s.FromContext(c)
  9. db := s.DB()
  10. if db == nil {
  11. ctx.Fail("数据库连接失败")
  12. return
  13. }
  14. type GroupWithSongs struct {
  15. entity.DtMusicGroup
  16. Songs []entity.DtMusic `json:"songs"`
  17. }
  18. // 获取所有启用的歌单
  19. groups := make([]*entity.DtMusicGroup, 0)
  20. db.Model(&entity.DtMusicGroup{}).
  21. Where("status = ?", 1).
  22. Order("sort ASC, id ASC").
  23. Find(&groups)
  24. // 获取所有启用的歌曲
  25. songs := make([]*entity.DtMusic, 0)
  26. db.Model(&entity.DtMusic{}).
  27. Where("status = ?", 1).
  28. Order("sort ASC, id ASC").
  29. Find(&songs)
  30. // 按歌单分组
  31. songMap := make(map[int64][]entity.DtMusic)
  32. for _, song := range songs {
  33. songMap[song.GroupId] = append(songMap[song.GroupId], *song)
  34. }
  35. result := make([]GroupWithSongs, 0)
  36. for _, group := range groups {
  37. item := GroupWithSongs{
  38. DtMusicGroup: *group,
  39. Songs: songMap[group.Id],
  40. }
  41. if item.Songs == nil {
  42. item.Songs = make([]entity.DtMusic, 0)
  43. }
  44. result = append(result, item)
  45. }
  46. ctx.OK(result)
  47. }