84 lines
1.7 KiB
Go
84 lines
1.7 KiB
Go
package dao
|
|
|
|
import (
|
|
"errors"
|
|
"fmt"
|
|
"yintai-api/app/common/model"
|
|
|
|
"gorm.io/gorm"
|
|
)
|
|
|
|
type Role struct {
|
|
db *gorm.DB
|
|
}
|
|
|
|
func NewRole(db ...*gorm.DB) *Role {
|
|
return &Role{db: getDB(db...)}
|
|
}
|
|
|
|
func (r *Role) TableName() string {
|
|
return "yt_role"
|
|
}
|
|
|
|
func (r *Role) Create(m *model.Role) error {
|
|
return r.db.Table(r.TableName()).Create(m).Error
|
|
}
|
|
|
|
func (r *Role) Update(m *model.Role) error {
|
|
return r.db.Table(r.TableName()).Save(m).Error
|
|
}
|
|
|
|
func (r *Role) Delete(id int64) error {
|
|
return r.db.Table(r.TableName()).Where("id = ?", id).Delete(&Role{}).Error
|
|
}
|
|
|
|
func (r *Role) Get(id int64) (*model.Role, error) {
|
|
var res model.Role
|
|
if err := r.db.Table(r.TableName()).Where("id = ?", id).First(&res).Error; err != nil {
|
|
if errors.Is(err, gorm.ErrRecordNotFound) {
|
|
return nil, nil
|
|
}
|
|
return nil, err
|
|
}
|
|
return &res, nil
|
|
}
|
|
|
|
func (r *Role) Exists(id int64) (bool, error) {
|
|
var count int64
|
|
if err := r.db.Table(r.TableName()).Where("id = ?", id).Count(&count).Error; err != nil {
|
|
return false, err
|
|
}
|
|
return count > 0, nil
|
|
}
|
|
|
|
func (r *Role) List(name, desc string, page, size int, sort string) ([]*model.Role, int64, error) {
|
|
var res []*model.Role
|
|
var count int64
|
|
tx := r.db.Table(r.TableName())
|
|
if name != "" {
|
|
tx = tx.Where("name LIKE ?", fmt.Sprintf("%%%s%%", name))
|
|
}
|
|
|
|
if desc != "" {
|
|
tx = tx.Where("desc LIKE ?", fmt.Sprintf("%%%s%%", desc))
|
|
}
|
|
|
|
if err := tx.Count(&count).Error; err != nil {
|
|
return nil, 0, err
|
|
}
|
|
|
|
if sort != "" {
|
|
tx = tx.Order(sort)
|
|
} else {
|
|
tx = tx.Order("id desc")
|
|
}
|
|
|
|
if err := tx.Offset((page - 1) * size).Limit(size).Find(&res).Error; err != nil {
|
|
if errors.Is(err, gorm.ErrRecordNotFound) {
|
|
return nil, 0, nil
|
|
}
|
|
return nil, 0, err
|
|
}
|
|
return res, count, nil
|
|
}
|