gorm 分页函数

package paginate

import (
	"math"

	"gorm.io/gorm"
)

// Param 分页参数
type Param struct {
	DB       *gorm.DB
	PageNo   int
	PageSize int
	OrderBy  []string
	ShowSQL  bool
}

// Paginator 分页返回
type Paginator struct {
	TotalCount int64       `json:"total_count"`
	TotalPage  int         `json:"total_page"`
	Records    interface{} `json:"records"`
	Current    int         `json:"current"`
	PageSize   int         `json:"page_size"`
}

// Paging 分页
func Paging[T any](p *Param, result *T) *Paginator {
	db := p.DB
	if p.ShowSQL {
		db = db.Debug()
	}
	if p.PageNo < 1 {
		p.PageNo = 1
	}
	if p.PageSize == 0 {
		p.PageSize = 10
	}

	done := make(chan bool, 1)
	var paginator Paginator
	var count int64
	var offset int

	go countRecords(db, result, done, &count)

	if p.PageNo == 1 {
		offset = 0
	} else {
		offset = (p.PageNo - 1) * p.PageSize
	}
	if len(p.OrderBy) > 0 {
		for _, o := range p.OrderBy {
			db = db.Order(o)
		}
	}
	db.Limit(p.PageSize).Offset(offset).Find(result)
	<-done

	paginator.TotalCount = count
	paginator.Records = result
	paginator.Current = p.PageNo
	paginator.PageSize = p.PageSize

	paginator.TotalPage = int(math.Ceil(float64(count) / float64(p.PageSize)))

	return &paginator
}

func countRecords(db *gorm.DB, anyType interface{}, done chan bool, count *int64) {
	db.Count(count)
	done <- true
}

func (l *GetRoleListLogic) GetRoleList(req *types.RoleReq) (resp *types.Pagina[types.RoleRes], err error) {

	records := []types.RoleRes{}

	pack := paginate.Paging[[]types.RoleRes](&paginate.Param{
		DB:       l.svcCtx.Gorm.Table("sys_role").Where(req),
		PageNo:   req.PageNo,
		PageSize: req.PageSize,
		OrderBy:  []string{"create_time DESC"},
		ShowSQL:  true,
	}, &records)

	return &types.Pagina[types.RoleRes]{
		TotalCount: pack.TotalCount,
		TotalPage:  pack.Current,
		Records:    records,
		Current:    pack.Current,
		PageSize:   pack.PageSize,
	}, nil
}

接受一个泛型,泛型为返回的数组对象,用于保存查询出来的结果

  • 6
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值