GORM分页插件
自己封装了一个GORM的分页插件
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77
| package paginate
import ( "fmt" "gorm.io/gorm" "math" )
type PageResp[T any] struct { TotalCount int64 `json:"total_count"` TotalPage int `json:"total_page"` Data []T `json:"data"` PageSize int `json:"page_size"` Page int `json:"page"` }
type PageReq struct { Page int `json:"page" form:"page"` PageSize int `json:"page_size" form:"page_size"` Sort int `json:"sort" form:"sort"` }
func Page[T any](db *gorm.DB, pageReq *PageReq, model T) (*PageResp[T], error) { var ( err error count int64 result PageResp[T] data []T ) err = db.Model(model).Count(&count).Error fmt.Println(count) if err := db.Model(model).Scopes(paginate(pageReq)).Scan(&data).Error; err != nil { return nil, err } result.TotalCount = count result.Data = data result.Page = pageReq.Page result.PageSize = pageReq.PageSize result.TotalPage = int(math.Ceil(float64(count) / float64(pageReq.PageSize))) return &result, err }
func paginate(pageReq *PageReq) func(db *gorm.DB) *gorm.DB { return func(db *gorm.DB) *gorm.DB { var ( page = pageReq.Page pageSize = pageReq.PageSize ) if page == 0 { page = 1 } switch { case pageSize > 1000: pageSize = 1000 case pageSize <= 0: pageSize = 10 } offset := (page - 1) * pageSize return db.Offset(offset).Limit(pageSize) } }
|