Files
mce/internal/service/category_service.go
Victor_Jay 0b8f6f890d feat: 分类系统 + 标签系统 — Phase 4 完成
分类:Model/Repo/Service/Controller + 管理后台树形页面 + 首页导航栏
标签:Model/Repo/Service/Controller + /tags/{slug} 落地页 + 写文章页输入
Post 加 CategoryID,Create/Update 支持分类和标签
SQL 迁移含 categories/tags/post_tags 表及预设未分类
2026-06-22 00:30:29 +08:00

76 lines
1.7 KiB
Go
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

package service
import "metazone.cc/mce/internal/model"
// CategoryStore 分类仓库接口ISP
type CategoryStore interface {
Create(c *model.Category) error
Update(c *model.Category) error
Delete(id uint) error
FindByID(id uint) (*model.Category, error)
ListAll() ([]model.Category, error)
GetLeaves() ([]model.Category, error)
}
// CategoryService 分类业务逻辑
type CategoryService struct {
repo CategoryStore
}
// NewCategoryService 构造函数
func NewCategoryService(repo CategoryStore) *CategoryService {
return &CategoryService{repo: repo}
}
// Create 创建分类
func (s *CategoryService) Create(c *model.Category) error {
return s.repo.Create(c)
}
// Update 更新分类
func (s *CategoryService) Update(c *model.Category) error {
return s.repo.Update(c)
}
// Delete 删除分类
func (s *CategoryService) Delete(id uint) error {
return s.repo.Delete(id)
}
// Tree 获取两级分类树
func (s *CategoryService) Tree() ([]model.Category, error) {
all, err := s.repo.ListAll()
if err != nil {
return nil, err
}
// 构建树parent_id=nil 的为根节点
parentMap := make(map[uint]*model.Category)
var roots []*model.Category
for i := range all {
c := &all[i]
c.Children = []model.Category{}
parentMap[c.ID] = c
if c.ParentID == nil {
roots = append(roots, c)
}
}
for i := range all {
c := &all[i]
if c.ParentID != nil {
if parent, ok := parentMap[*c.ParentID]; ok {
parent.Children = append(parent.Children, *c)
}
}
}
result := make([]model.Category, len(roots))
for i, r := range roots {
result[i] = *r
}
return result, nil
}
// GetLeaves 获取所有叶子分类(用于写文章页下拉选择)
func (s *CategoryService) GetLeaves() ([]model.Category, error) {
return s.repo.GetLeaves()
}