This repository has been archived on 2024-11-28. You can view files and clone it, but cannot push or open issues or pull requests.
Files
schisandra-cloud-album/utils/paginator.go
2024-09-23 00:53:43 +08:00

53 lines
1.3 KiB
Go
Raw Permalink Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

package utils
import (
"gorm.io/gorm"
)
// 标准分页结构体接收最原始的DO
// 建议在外部再建一个字段一样的结构体用以将DO转换成DTO或VO
type Page[T any] struct {
CurrentPage int64 `json:"currentPage"`
PageSize int64 `json:"pageSize"`
Total int64 `json:"total"`
Pages int64 `json:"pages"`
Data []T `json:"data"`
}
// 各种查询条件先在query设置好后再放进来
func (page *Page[T]) SelectPages(query *gorm.DB) (e error) {
var model T
query.Model(&model).Count(&page.Total)
if page.Total == 0 {
page.Data = []T{}
return
}
e = query.Model(&model).Scopes(Paginate(page)).Find(&page.Data).Error
return
}
func Paginate[T any](page *Page[T]) func(db *gorm.DB) *gorm.DB {
return func(db *gorm.DB) *gorm.DB {
if page.CurrentPage <= 0 {
page.CurrentPage = 1
}
switch {
case page.PageSize > 10000:
page.PageSize = 10000 // 限制一下分页大小
case page.PageSize <= 0:
page.PageSize = 10
}
page.Pages = page.Total / page.PageSize
if page.Total%page.PageSize != 0 {
page.Pages++
}
p := page.CurrentPage
if page.CurrentPage > page.Pages {
p = page.Pages
}
size := page.PageSize
offset := int((p - 1) * size)
return db.Offset(offset).Limit(int(size))
}
}