dbutils.go 688 B

123456789101112131415161718192021222324
  1. package helper
  2. import "gorm.io/gorm"
  3. // QueryByConditions 通用多条查询
  4. func QueryByCondition[T any](db *gorm.DB, conditions map[string]interface{}) ([]T, error) {
  5. var results []T
  6. tx := db.Where(conditions).Find(&results)
  7. return results, tx.Error
  8. }
  9. // QueryByConditions 分页查询
  10. func QueryByConditions[T any](db *gorm.DB, conditions map[string]interface{}, pageNum, pageSize int) ([]T, int64, error) {
  11. var results []T
  12. var total int64
  13. tx := db.Where(conditions).Model(&results).Count(&total)
  14. if tx.Error != nil {
  15. return nil, 0, tx.Error
  16. }
  17. tx = db.Where(conditions).Offset((pageNum - 1) * pageSize).Limit(pageSize).Find(&results)
  18. return results, total, tx.Error
  19. }