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.

125 lines
2.2 KiB

package models
import (
"fmt"
"gorm.io/gorm"
"product/backend/moo/db"
)
type Role struct {
// body
Title string `gorm:"type:varchar(255);uniqueIndex" json:"title"`
Key string `gorm:"type:varchar(255);uniqueIndex" json:"key"`
Order int `gorm:"" json:"order"`
State bool `gorm:"" json:"state"`
Remark string `gorm:"type:varchar(255)" json:"remark"`
// body association field
Privs string `gorm:"type:varchar(2047)" json:"privs"`
// basic models
Model
// association
Users []User `json:"users"`
}
// methods
func RoleRow(id uint) (Role, error) {
// model
row := Role{}
if err := db.DB.First(&row, id).Error; err != nil {
return row, err
}
// with association
return row, nil
}
func RoleRows(pager Pager, withTotal bool, keyword string) ([]Role, int64, error) {
// query
query := db.DB.Model(&Role{})
// filter
// keyword
if keyword != "" {
query.Where("title LIKE ? OR `key` LIKE ?", keyword+"%", keyword+"%")
}
// fetch total
var total int64
if withTotal {
query.Count(&total)
}
// order
query.Order(fmt.Sprintf("`%s` %s", pager.SortField, pager.SortOrder))
// # offset limit
offset := -1 // 不限制
if pager.PageSize > 0 {
offset = (pager.PageIndex - 1) * pager.PageSize
}
query.Offset(offset).Limit(pager.PageSize)
// select
query.Select("*")
// fetch
var rows []Role
if result := query.Debug().Find(&rows); result.Error != nil {
return rows, 0, result.Error
}
// with association
return rows, total, nil
}
func RoleRowDel(id uint) error {
// db tx
return db.DB.Transaction(func(tx *gorm.DB) error {
// model delete
if result := tx.Delete(&Role{}, id); result.Error != nil {
return result.Error
}
// association delete
return nil
})
}
func RoleRowUpdate(model *Role) error {
// db tx
return db.DB.Transaction(func(tx *gorm.DB) error {
// model update
if result := tx.Updates(&model); result.Error != nil {
return result.Error
}
// association update
return nil
})
}
func RoleRowInsert(model *Role) error {
// default value
// db tx
return db.DB.Transaction(func(tx *gorm.DB) error {
// model create
if result := tx.Create(&model); result.Error != nil {
return result.Error
}
// association create
return nil
})
}