Files
sundynix-radio-be/service/radio/category_service.go
T
2026-03-06 17:39:52 +08:00

98 lines
2.7 KiB
Go

package radio
import (
"errors"
"sundynix-go/global"
"sundynix-go/model/radio"
radioReq "sundynix-go/model/radio/request"
"gorm.io/gorm"
)
type CategoryService struct{}
// GetCategoryList 获取分类列表
func (s *CategoryService) GetCategoryList(info radioReq.GetCategoryList) ([]radio.RadioCategory, int64, error) {
db := global.DB.Model(&radio.RadioCategory{})
var list []radio.RadioCategory
var total int64
if info.Name != "" {
db = db.Where("name LIKE ?", "%"+info.Name+"%")
}
if info.Status > 0 {
db = db.Where("status = ?", info.Status)
}
err := db.Count(&total).Error
if err != nil {
return nil, 0, err
}
offset := (info.Current - 1) * info.PageSize
err = db.Offset(offset).Limit(info.PageSize).Order("sort ASC").Find(&list).Error
return list, total, err
}
// GetCategoryTree 返回带频道的分类树
func (s *CategoryService) GetCategoryTree() ([]radio.RadioCategory, error) {
var res []radio.RadioCategory
// 1. 查询分类并预加载关联的频道
// Preload("Channels") 会自动根据 CategoryId 匹配
// Preload("Icon") 和 Preload("Cover") 用于加载 OSS 信息
err := global.DB.Model(&radio.RadioCategory{}).
Preload("Channels", "status = ?", 1). // 只加载启用的频道
Order("sort desc").
Find(&res).Error
return res, err
}
func (s *CategoryService) GetAllCategory() ([]radio.RadioCategory, error) {
var res []radio.RadioCategory
err := global.DB.Find(&res).Error
return res, err
}
// GetCategoryById 获取分类详情
func (s *CategoryService) GetCategoryById(id string) (*radio.RadioCategory, error) {
var category radio.RadioCategory
err := global.DB.Where("id = ?", id).First(&category).Error
return &category, err
}
// SaveCategory 保存分类
func (s *CategoryService) SaveCategory(req radioReq.SaveCategory) error {
category := radio.RadioCategory{
Name: req.Name,
Description: req.Description,
Sort: req.Sort,
Status: req.Status,
}
return global.DB.Create(&category).Error
}
// UpdateCategory 更新分类
func (s *CategoryService) UpdateCategory(req radioReq.UpdateCategory) error {
updates := map[string]interface{}{
"name": req.Name,
"description": req.Description,
"sort": req.Sort,
"status": req.Status,
}
return global.DB.Model(&radio.RadioCategory{}).Where("id = ?", req.Id).Updates(updates).Error
}
// DeleteCategory 删除分类
func (s *CategoryService) DeleteCategory(id string) error {
return global.DB.Transaction(func(tx *gorm.DB) error {
// 检查是否有频道使用此分类
var count int64
tx.Model(&radio.RadioChannel{}).Where("category_id = ?", id).Count(&count)
if count > 0 {
return errors.New("该分类下存在频道,无法删除")
}
return tx.Where("id = ?", id).Delete(&radio.RadioCategory{}).Error
})
}