1 Star 0 Fork 0

鹰厂长 / ycz

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
克隆/下载
pagination.go 1.01 KB
一键复制 编辑 原始数据 按行查看 历史
chaitao 提交于 2023-08-11 10:37 . 优化
package base
import (
"context"
"gorm.io/gorm"
"gorm.io/gorm/schema"
"sync"
)
const MaxPageSize = 10000
type Pagination[T schema.Tabler] struct {
once sync.Once
Query *gorm.DB
Error error
Size int
Page int
total int64
items []T
}
func (p *Pagination[T]) Total() int64 {
return p.total
}
func (p *Pagination[T]) Items() []T {
return p.items
}
func (p *Pagination[T]) Load() *Pagination[T] {
p.once.Do(func() {
if p.Size == 0 {
p.Page = 1
p.Size = MaxPageSize
}
query := p.Query
if p.Query.Statement.Model == nil {
var t T
query = query.Model(t).Table(t.TableName() + " AS Main")
} else {
query = query.Table(query.Statement.Model.(schema.Tabler).TableName() + " AS Main")
}
p.Error = query.WithContext(context.Background()).Count(&p.total).Error
if p.Error != nil {
return
}
page := p.Page - 1
if page < 0 {
page = 0
}
offset := page * p.Size
p.Error = query.WithContext(context.Background()).Offset(offset).Limit(p.Size).Find(&p.items).Error
})
return p
}
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化
Go
1
https://gitee.com/ycz-new/ycz.git
git@gitee.com:ycz-new/ycz.git
ycz-new
ycz
ycz
39e396945b70

搜索帮助

344bd9b3 5694891 D2dac590 5694891