menu.go 2.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081
  1. package dao
  2. // Menu 角色
  3. type Menu struct {
  4. ID int `gorm:"type:int;primary_key" json:"id"` //编号
  5. ParentId int `gorm:"type:int;default 0" json:"parentId"` //父级菜单
  6. Code string `gorm:"type:varchar(255)" json:"code"` //菜单编号
  7. Name string `gorm:"type:varchar(255)" json:"name"` //菜单名称
  8. Alias string `gorm:"type:varchar(255)" json:"alias"` //菜单别名
  9. Path string `gorm:"type:varchar(255)" json:"path"` //请求地址
  10. Source string `gorm:"type:varchar(255)" json:"source"` //菜单资源
  11. Sort int `gorm:"type:int" json:"sort"` //排序
  12. Category int `gorm:"type:int" json:"category"` //菜单类型
  13. Action int `gorm:"type:int;default 0" json:"action"` //操作按钮类型
  14. IsOpen int `gorm:"type:int;default 1" json:"isOpen"` //是否打开新页面
  15. Remark string `gorm:"type:varchar(255)" json:"remark"` //备注
  16. IsDeleted int `gorm:"type:int" json:"isDeleted"` //是否删除
  17. }
  18. func (Menu) TableName() string {
  19. return "menu"
  20. }
  21. func (c *Menu) Get() error {
  22. return Db.Model(&c).Where("id = ?", c.ID).Find(&c).Error
  23. }
  24. func (c *Menu) Save() error {
  25. return Db.Model(&c).Save(&c).Error
  26. }
  27. func (c *Menu) Update() error {
  28. return Db.Model(&c).Where(" id = ? ", c.ID).Updates(&c).Error
  29. }
  30. func (c *Menu) GetAll() ([]Menu, error) {
  31. var menus []Menu
  32. err := Db.Model(&c).Where(" is_deleted = 0 and category = 1").Order("sort").Find(&menus).Error
  33. return menus, err
  34. }
  35. func (c *Menu) GetByParentId() ([]Menu, error) {
  36. var menus []Menu
  37. db := Db.Model(&c).Where(" is_deleted = 0")
  38. if c.ParentId >= 0 {
  39. db = db.Where("parent_id = ?", c.ParentId)
  40. }
  41. if c.Name != "" {
  42. db = db.Where("name like ?", "%"+c.Name+"%")
  43. }
  44. if c.Code != "" {
  45. db = db.Where("code like ?", "%"+c.Code+"%")
  46. }
  47. if c.Alias != "" {
  48. db = db.Where("alias like ?", "%"+c.Alias+"%")
  49. }
  50. err := db.Order("sort").Find(&menus).Error
  51. return menus, err
  52. }
  53. func (c *Menu) HasChildren(parentIds []int) (map[int]bool, error) {
  54. type hasChildren struct {
  55. ParentId int `gorm:"type:int"`
  56. Count int `gorm:"type:int"`
  57. }
  58. var result []hasChildren
  59. err := Db.Table("menu").Select("parent_id, count(*) count").Where(" is_deleted = 0 and parent_id in (?)", parentIds).Group("parent_id").Find(&result).Error
  60. m := make(map[int]bool)
  61. for _, item := range result {
  62. m[item.ParentId] = item.Count > 0
  63. }
  64. return m, err
  65. }
  66. // todo 查询菜单树,只查id,parent_id和name
  67. func (c *Menu) GetMenuTree() ([]Menu, error) {
  68. var menus []Menu
  69. err := Db.Model(&c).Select("id,name,parent_id").Where(" is_deleted = 0 and category = 1").Order("sort").Find(&menus).Error
  70. return menus, err
  71. }