componentClassify.go 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  1. package model
  2. import (
  3. "Panel_development/global"
  4. "errors"
  5. "gorm.io/gorm"
  6. )
  7. type ComponentClassify struct {
  8. gorm.Model
  9. Name string `gorm:"type:varchar(255);not null;unique;comment:组件分类名称" json:"name" validate:"required"`
  10. ParentId uint `gorm:"type:int;not null;comment:父组件id" json:"parentId"`
  11. Child []ComponentClassify `gorm:"-" json:"child"` // 此字段将不会被GORM迁移至数据库
  12. }
  13. func (cc ComponentClassify) TableName() string {
  14. return "component_classify"
  15. }
  16. // AddComponentClassify 添加组件分类
  17. func (cc ComponentClassify) AddComponentClassify(cclass ComponentClassify) (ComponentClassify, error) {
  18. //TODO implement me
  19. tx := global.DBLink.Create(&cclass)
  20. if tx.RowsAffected > 0 {
  21. return ComponentClassify{}, nil
  22. }
  23. return ComponentClassify{}, errors.New("添加失败")
  24. }
  25. // GetComponentClassify 获取组件分类
  26. func (cc ComponentClassify) GetComponentClassify() ([]ComponentClassify, error) {
  27. var roots []ComponentClassify
  28. err := global.DBLink.Where("parent_id = 0").Find(&roots).Error
  29. if err != nil {
  30. return nil, err
  31. }
  32. for i := range roots {
  33. err = recursiveFetchChildren(global.DBLink, &roots[i])
  34. if err != nil {
  35. return nil, err
  36. }
  37. }
  38. return roots, nil
  39. }
  40. // 递归获取分类
  41. func recursiveFetchChildren(db *gorm.DB, parent *ComponentClassify) error {
  42. var children []ComponentClassify
  43. err := db.Where("parent_id = ?", parent.ID).Find(&children).Error
  44. if err != nil {
  45. return err
  46. }
  47. for _, child := range children {
  48. err = recursiveFetchChildren(db, &child)
  49. if err != nil {
  50. return err
  51. }
  52. parent.Child = append(parent.Child, child)
  53. }
  54. return nil
  55. }