You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
83 lines
2.3 KiB
83 lines
2.3 KiB
package model
|
|
|
|
import (
|
|
"context"
|
|
"errors"
|
|
|
|
"gorm.io/gorm"
|
|
)
|
|
|
|
// MenuInsert 插入菜单
|
|
func MenuInsert(ctx context.Context, db *gorm.DB, menu *Menu) (int64, error) {
|
|
result := db.WithContext(ctx).Create(menu)
|
|
if result.Error != nil {
|
|
return 0, result.Error
|
|
}
|
|
return menu.Id, nil
|
|
}
|
|
|
|
// MenuFindOne 根据ID查询菜单
|
|
func MenuFindOne(ctx context.Context, db *gorm.DB, id int64) (*Menu, error) {
|
|
var menu Menu
|
|
result := db.WithContext(ctx).First(&menu, id)
|
|
if result.Error != nil {
|
|
if errors.Is(result.Error, gorm.ErrRecordNotFound) {
|
|
return nil, ErrNotFound
|
|
}
|
|
return nil, result.Error
|
|
}
|
|
return &menu, nil
|
|
}
|
|
|
|
// MenuFindAll 查询所有启用的菜单(排序)
|
|
func MenuFindAll(ctx context.Context, db *gorm.DB) ([]Menu, error) {
|
|
var menus []Menu
|
|
err := db.WithContext(ctx).Where("status = 1").Order("sort_order ASC, id ASC").Find(&menus).Error
|
|
return menus, err
|
|
}
|
|
|
|
// MenuFindByIds 根据ID列表查询菜单
|
|
func MenuFindByIds(ctx context.Context, db *gorm.DB, ids []int64) ([]Menu, error) {
|
|
var menus []Menu
|
|
if len(ids) == 0 {
|
|
return menus, nil
|
|
}
|
|
err := db.WithContext(ctx).Where("id IN ? AND status = 1", ids).Order("sort_order ASC, id ASC").Find(&menus).Error
|
|
return menus, err
|
|
}
|
|
|
|
// MenuUpdate 更新菜单
|
|
func MenuUpdate(ctx context.Context, db *gorm.DB, menu *Menu) error {
|
|
return db.WithContext(ctx).Save(menu).Error
|
|
}
|
|
|
|
// MenuDelete 删除菜单
|
|
func MenuDelete(ctx context.Context, db *gorm.DB, id int64) error {
|
|
return db.WithContext(ctx).Delete(&Menu{}, id).Error
|
|
}
|
|
|
|
// MenuBatchUpdateSort 批量更新菜单排序和父级
|
|
func MenuBatchUpdateSort(ctx context.Context, db *gorm.DB, items []struct {
|
|
Id int64
|
|
SortOrder int
|
|
ParentId int64
|
|
}) error {
|
|
return db.WithContext(ctx).Transaction(func(tx *gorm.DB) error {
|
|
for _, item := range items {
|
|
if err := tx.Model(&Menu{}).Where("id = ?", item.Id).Updates(map[string]interface{}{
|
|
"sort_order": item.SortOrder,
|
|
"parent_id": item.ParentId,
|
|
}).Error; err != nil {
|
|
return err
|
|
}
|
|
}
|
|
return nil
|
|
})
|
|
}
|
|
|
|
// MenuHasChildren 检查菜单是否有子菜单
|
|
func MenuHasChildren(ctx context.Context, db *gorm.DB, parentId int64) (bool, error) {
|
|
var count int64
|
|
err := db.WithContext(ctx).Model(&Menu{}).Where("parent_id = ?", parentId).Count(&count).Error
|
|
return count > 0, err
|
|
}
|
|
|