123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263 |
- package model
- import (
- "Panel_development/global"
- "errors"
- "gorm.io/gorm"
- )
- type ComponentClassify struct {
- gorm.Model
- Name string `gorm:"type:varchar(255);not null;unique;comment:组件分类名称" json:"name" validate:"required"`
- ParentId uint `gorm:"type:int;not null;comment:父组件id" json:"parentId"`
- Child []ComponentClassify `gorm:"-" json:"child"` // 此字段将不会被GORM迁移至数据库
- }
- func (cc ComponentClassify) TableName() string {
- return "component_classify"
- }
- // AddComponentClassify 添加组件分类
- func (cc ComponentClassify) AddComponentClassify(cclass ComponentClassify) (ComponentClassify, error) {
- //TODO implement me
- tx := global.DBLink.Create(&cclass)
- if tx.RowsAffected > 0 {
- return ComponentClassify{}, nil
- }
- return ComponentClassify{}, errors.New("添加失败")
- }
- // GetComponentClassify 获取组件分类
- func (cc ComponentClassify) GetComponentClassify() ([]ComponentClassify, error) {
- var roots []ComponentClassify
- err := global.DBLink.Where("parent_id = 0").Find(&roots).Error
- if err != nil {
- return nil, err
- }
- for i := range roots {
- err = recursiveFetchChildren(global.DBLink, &roots[i])
- if err != nil {
- return nil, err
- }
- }
- return roots, nil
- }
- // 递归获取分类
- func recursiveFetchChildren(db *gorm.DB, parent *ComponentClassify) error {
- var children []ComponentClassify
- err := db.Where("parent_id = ?", parent.ID).Find(&children).Error
- if err != nil {
- return err
- }
- for _, child := range children {
- err = recursiveFetchChildren(db, &child)
- if err != nil {
- return err
- }
- parent.Child = append(parent.Child, child)
- }
- return nil
- }
|