增加同时获取数量和列表的方法

This commit is contained in:
2025-02-26 17:29:30 +08:00
parent 2b23dd7714
commit 2f573767e1
3 changed files with 109 additions and 26 deletions

38
base.go
View File

@ -8,8 +8,8 @@ package database
import (
"errors"
"git.zhangdeman.cn/zhangdeman/database/define"
"gorm.io/gorm"
"reflect"
)
// BaseDao 基础dao层
@ -69,6 +69,35 @@ func (b *BaseDao) List(dbInstance *gorm.DB, result any, optionFuncList ...define
return dbInstance.Find(result).Error
}
// ListAndTotal 同时查询数据列表和数据总数
//
// Author : go_developer@163.com<白茶清欢>
//
// Date : 16:04 2025/2/26
func (b *BaseDao) ListAndTotal(dbInstance *gorm.DB, listRes any, disableTotal bool, optionFuncList ...define.SetOption) (int64, error) {
if err := b.receiverTypeValid(listRes); nil != err {
return 0, err
}
var (
cnt int64
err error
)
dbInstance = b.setTxCondition(dbInstance, optionFuncList...)
if err = dbInstance.Find(listRes).Error; nil != err {
// 列表查询失败
return 0, err
}
if disableTotal {
// 禁用查询总数
return int64(reflect.ValueOf(listRes).Elem().Len()), nil
}
if err = dbInstance.Count(&cnt).Error; nil != err {
return 0, err
}
return cnt, nil
}
// Delete 删除数据, 硬删除, 对应 delete语句
//
// Author : go_developer@163.com<白茶清欢>
@ -285,3 +314,10 @@ func (b *BaseDao) setTxCondition(tx *gorm.DB, optionFuncList ...define.SetOption
}*/
return tx
}
func (b *BaseDao) receiverTypeValid(receiver any) error {
if receiver == nil || reflect.TypeOf(receiver).Kind() != reflect.Ptr {
return errors.New("receiver is nil or receiver is not a pointer")
}
return nil
}