exa_attachment_category.go 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  1. package example
  2. import (
  3. "errors"
  4. "github.com/flipped-aurora/gin-vue-admin/server/global"
  5. "github.com/flipped-aurora/gin-vue-admin/server/model/example"
  6. "gorm.io/gorm"
  7. )
  8. type AttachmentCategoryService struct{}
  9. // AddCategory 创建/更新的分类
  10. func (a *AttachmentCategoryService) AddCategory(req *example.ExaAttachmentCategory) (err error) {
  11. // 检查是否已存在相同名称的分类
  12. if (!errors.Is(global.GVA_DB.Take(&example.ExaAttachmentCategory{}, "name = ? and pid = ?", req.Name, req.Pid).Error, gorm.ErrRecordNotFound)) {
  13. return errors.New("分类名称已存在")
  14. }
  15. if req.ID > 0 {
  16. if err = global.GVA_DB.Model(&example.ExaAttachmentCategory{}).Where("id = ?", req.ID).Updates(&example.ExaAttachmentCategory{
  17. Name: req.Name,
  18. Pid: req.Pid,
  19. }).Error; err != nil {
  20. return err
  21. }
  22. } else {
  23. if err = global.GVA_DB.Create(&example.ExaAttachmentCategory{
  24. Name: req.Name,
  25. Pid: req.Pid,
  26. }).Error; err != nil {
  27. return err
  28. }
  29. }
  30. return nil
  31. }
  32. // DeleteCategory 删除分类
  33. func (a *AttachmentCategoryService) DeleteCategory(id *int) error {
  34. var childCount int64
  35. global.GVA_DB.Model(&example.ExaAttachmentCategory{}).Where("pid = ?", id).Count(&childCount)
  36. if childCount > 0 {
  37. return errors.New("请先删除子级")
  38. }
  39. return global.GVA_DB.Where("id = ?", id).Unscoped().Delete(&example.ExaAttachmentCategory{}).Error
  40. }
  41. // GetCategoryList 分类列表
  42. func (a *AttachmentCategoryService) GetCategoryList() (res []*example.ExaAttachmentCategory, err error) {
  43. var fileLists []example.ExaAttachmentCategory
  44. err = global.GVA_DB.Model(&example.ExaAttachmentCategory{}).Find(&fileLists).Error
  45. if err != nil {
  46. return res, err
  47. }
  48. return a.getChildrenList(fileLists, 0), nil
  49. }
  50. // getChildrenList 子类
  51. func (a *AttachmentCategoryService) getChildrenList(categories []example.ExaAttachmentCategory, parentID uint) []*example.ExaAttachmentCategory {
  52. var tree []*example.ExaAttachmentCategory
  53. for _, category := range categories {
  54. if category.Pid == parentID {
  55. category.Children = a.getChildrenList(categories, category.ID)
  56. tree = append(tree, &category)
  57. }
  58. }
  59. return tree
  60. }