1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677 |
- 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迁移至数据库
- }
- type ComponentClassifyDto struct {
- Id int `json:"id"`
- 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
- }
- func UpdateByIds(id int, tableName string, model ComponentClassifyDto) (ComponentClassifyDto, error) {
- tx := global.DBLink.Table(tableName).Where("id = ?", id).Updates(&model)
- if tx.RowsAffected > 0 {
- return model, nil
- } else {
- return model, errors.New("修改失败当前id不存在")
- }
- }
|