代码拉取完成,页面将自动刷新
// service/IService.go
package base
import (
"errors"
"fmt"
"reflect"
"strings"
"gitee.com/linqwen/momo/utils"
"gorm.io/gorm"
)
type BaseService[model IModel] struct {
DB *gorm.DB
Model model
}
type IBaseService[T IModel] interface {
Create(model *T) (*T, error)
BulkCreate(models []T) (int, []T, error)
GetById(id string) (*T, error)
Update(id string, model T) (*T, error)
Delete(id string) error
BulkDelete(ids []string) (int, error)
PageByMap(queryDto map[string]any, queryPage *QueryPage) (*[]T, int, error)
GetTreeById(id string) ([]T, error)
UpdateByMap(id string, dtoMap map[string]interface{}) error
}
func NewBaseService[T IModel](db *gorm.DB, model T) *BaseService[T] {
return &BaseService[T]{
DB: db,
Model: model,
}
}
func (bs *BaseService[T]) Create(model *T) (*T, error) {
result := bs.DB.Create(&model)
if result.Error != nil {
return nil, result.Error
}
return model, nil
}
func (bs *BaseService[T]) BulkCreate(models []T) (int, []T, error) {
result := bs.DB.Create(models)
if result.Error != nil {
return int(result.RowsAffected), models, result.Error
}
return int(result.RowsAffected), models, nil
}
func (bs *BaseService[T]) GetById(id string) (*T, error) {
var result T
query := bs.DB
if err := query.First(&result, "id = ?", id).Error; err != nil {
if errors.Is(err, gorm.ErrRecordNotFound) {
return nil, err
}
return nil, err
}
return &result, nil
}
func (bs *BaseService[T]) Update(id string, model T) (*T, error) {
result := bs.DB.Model(&model).Where("id = ?", id).Updates(model)
if err := result.Error; err != nil {
return nil, err
}
if result.RowsAffected == 0 {
return nil, fmt.Errorf("entity with id '%s' not found", id)
}
return &model, nil
}
func (bs *BaseService[T]) UpdateByMap(id string, dtoMap map[string]interface{}) error {
if err := bs.DB.Model(&bs.Model).Where("id = ?", id).Updates(&dtoMap).Error; err != nil {
return err
}
return nil
}
func (bs *BaseService[T]) Delete(id string) error {
if err := bs.DB.Where("id = ?", id).Delete(&bs.Model).Error; err != nil {
return err
}
return nil
}
func (bs *BaseService[T]) BulkDelete(ids []string) (int, error) {
result := bs.DB.Where("id IN ?", ids).Delete(&bs.Model)
if result.Error != nil {
return 0, nil
}
return int(result.RowsAffected), nil
}
// applySorting 处理排序逻辑
func applySorting(query *gorm.DB, model interface{}, ascs, descs []string) {
if len(ascs) == 0 && len(descs) == 0 {
if hasSortField(model) {
query.Order("sort DESC,id DESC")
} else {
query.Order("id DESC")
}
} else {
for _, asc := range ascs {
query.Order(asc + " ASC")
}
for _, desc := range descs {
query.Order(desc + " DESC")
}
}
}
func (bs *BaseService[T]) PageByMap(queryMap map[string]interface{}, queryPage *QueryPage) (*[]T, int, error) {
offset := (queryPage.Current - 1) * queryPage.Size
query := bs.DB.Model(bs.Model)
applySorting(query, bs.Model, queryPage.Ascs, queryPage.Descs)
var models []T
// dtoMap, _ := utils.StructToMapWithColumn(queryDto)
if len(queryMap) > 0 {
// 处理不同类型的查询条件
for k, v := range queryMap {
if gte, ok := strings.CutSuffix(k, "_ge"); ok {
if !utils.ReflectUtil.IsEmptyValue(reflect.ValueOf(v)) {
query.Where(fmt.Sprintf("%s >= ?", gte), v)
}
} else if gt, ok := strings.CutSuffix(k, "_gt"); ok {
if !utils.ReflectUtil.IsEmptyValue(reflect.ValueOf(v)) {
query.Where(fmt.Sprintf("%s > ?", gt), v)
}
} else if lte, ok := strings.CutSuffix(k, "_le"); ok {
if !utils.ReflectUtil.IsEmptyValue(reflect.ValueOf(v)) {
query.Where(fmt.Sprintf("%s >= ?", lte), v)
}
} else if lt, ok := strings.CutSuffix(k, "_lt"); ok {
if !utils.ReflectUtil.IsEmptyValue(reflect.ValueOf(v)) {
query.Where(fmt.Sprintf("%s < ?", lt), v)
}
} else if datelt, ok := strings.CutSuffix(k, "_datelt"); ok {
if !utils.ReflectUtil.IsEmptyValue(reflect.ValueOf(v)) {
query.Where(fmt.Sprintf("%s < ?", datelt), v)
}
} else if datelte, ok := strings.CutSuffix(k, "_datele"); ok {
if !utils.ReflectUtil.IsEmptyValue(reflect.ValueOf(v)) {
query.Where(fmt.Sprintf("%s <= ?", datelte), v)
}
} else if dategt, ok := strings.CutSuffix(k, "_dategt"); ok {
if !utils.ReflectUtil.IsEmptyValue(reflect.ValueOf(v)) {
query.Where(fmt.Sprintf("%s > ?", dategt), v)
}
} else if dategte, ok := strings.CutSuffix(k, "_datege"); ok {
if !utils.ReflectUtil.IsEmptyValue(reflect.ValueOf(v)) {
query.Where(fmt.Sprintf("%s >= ?", dategte), v)
}
} else if like, ok := strings.CutSuffix(k, "_like"); ok {
if !utils.ReflectUtil.IsEmptyValue(reflect.ValueOf(v)) {
s := v.(string)
if !utils.ReflectUtil.IsEmptyValue(reflect.ValueOf(v)) {
query.Where(fmt.Sprintf("%s like ?", like), "%"+s+"%")
}
}
} else if likeleft, ok := strings.CutSuffix(k, "_likeleft"); ok {
if !utils.ReflectUtil.IsEmptyValue(reflect.ValueOf(v)) {
s := v.(string)
if !utils.ReflectUtil.IsEmptyValue(reflect.ValueOf(v)) {
query.Where(fmt.Sprintf("%s like ?", likeleft), s+"%")
}
}
} else if eq, ok := strings.CutSuffix(k, "_eq"); ok {
if !utils.ReflectUtil.IsEmptyValue(reflect.ValueOf(v)) {
s := v.(string)
if !utils.ReflectUtil.IsEmptyValue(reflect.ValueOf(v)) {
query.Where(fmt.Sprintf("%s = ?", eq), s)
}
}
} else {
if !utils.ReflectUtil.IsEmptyValue(reflect.ValueOf(v)) {
query.Where(fmt.Sprintf("%s = ?", k), v)
}
}
}
}
var count int64
if err := query.Count(&count).Error; err != nil {
return nil, 0, err
}
if err := query.Offset(offset).Limit(queryPage.Size).Find(&models).Error; err != nil {
if errors.Is(err, gorm.ErrRecordNotFound) {
return nil, 0, errors.New("no records found matching the given criteria")
}
return nil, 0, err
}
return &models, int(count), nil
}
// 根据 [Id] 查询记录返回 [树形切片]
func (bs *BaseService[T]) GetTreeById(id string) ([]T, error) {
var result []T
// 创建查询对象
query := bs.DB
// 检查模型是否具有 order 字段
var model T
if hasSortField(model) {
query = query.Order("sort DESC")
}
tableName := model.TableName()
sel := fmt.Sprintf("%s.*, (SELECT CASE WHEN count(1) > 0 THEN true ELSE false END FROM %s m WHERE m.parent_id = %s.id) AS HasChildren", tableName, tableName, tableName)
if err := query.Where("parent_id = ?", id).Select(sel).Find(&result).Error; err != nil {
if errors.Is(err, gorm.ErrRecordNotFound) {
return nil, err
}
return nil, err
}
return result, nil
}
func hasSortField(model interface{}) bool {
val := reflect.ValueOf(model)
if val.Kind() == reflect.Ptr {
val = val.Elem()
}
if val.Kind() != reflect.Struct {
return false
}
field := val.FieldByName("Sort")
return field.IsValid()
}
此处可能存在不合适展示的内容,页面不予展示。您可通过相关编辑功能自查并修改。
如您确认内容无涉及 不当用语 / 纯广告导流 / 暴力 / 低俗色情 / 侵权 / 盗版 / 虚假 / 无价值内容或违法国家有关法律法规的内容,可点击提交进行申诉,我们将尽快为您处理。