Skip to content

Commit

Permalink
Merge pull request #7 from toufiq-austcse/master
Browse files Browse the repository at this point in the history
fix: total count issue in pagination gorm
  • Loading branch information
Shipu committed Aug 21, 2024
2 parents 2d452b8 + ce4ff44 commit 4a5e055
Showing 1 changed file with 26 additions and 11 deletions.
37 changes: 26 additions & 11 deletions pagination.go
Original file line number Diff line number Diff line change
Expand Up @@ -10,24 +10,41 @@ import (
var Pagination paginator.Paginator

type PaginationMeta struct {
CurrentPage int `json:"current_page"`
PerPage int `json:"per_page"`
LastPage int `json:"last_page"`
Total int `json:"total"`
CurrentPage int `json:"current_page"`
PerPage int `json:"per_page"`
LastPage int `json:"last_page"`
Total int64 `json:"total"`
}

type Paginator struct {
Meta PaginationMeta `json:"meta"`
db *gorm.DB
*paginator.Paginator
model interface{}
filter map[string]interface{}
}

func (paginator *Paginator) PaginateScope() func(db *gorm.DB) *gorm.DB {
func (paginator *Paginator) PaginateScope(page int, limit int) func(db *gorm.DB) *gorm.DB {
if page == 0 {
page = 1
}
if limit == 0 {
limit = 10
}
var totalRows int64

paginator.Meta.CurrentPage = page
paginator.Meta.PerPage = limit

DB.Model(paginator.model).Where(paginator.filter).Count(&totalRows)
paginator.Meta.Total = totalRows
paginator.Meta.LastPage = int(math.Ceil(float64(totalRows) / float64(limit)))

return func(db *gorm.DB) *gorm.DB {
offset := (paginator.Meta.CurrentPage - 1) * paginator.Meta.PerPage
return db.Offset(offset).Limit(paginator.Meta.PerPage)
}
}

func (paginator *Paginator) CursorPaginate(query *gorm.DB, v interface{}) (*gorm.DB, paginator.Cursor, error) {
return paginator.Paginate(query, v)
}
Expand Down Expand Up @@ -57,11 +74,11 @@ func (paginator *Paginator) updateMeta(v interface{}, request map[string]interfa

var totalRows int64
DB.Model(v).Count(&totalRows)
paginator.Meta.Total = int(totalRows)
paginator.Meta.Total = totalRows
paginator.Meta.LastPage = int(math.Ceil(float64(totalRows) / float64(limit)))
}

func NewPaginator(v interface{}, request map[string]interface{}) *Paginator {
func NewPaginator(v interface{}, queryFilter map[string]interface{}) *Paginator {
opts := []paginator.Option{
&paginator.Config{
Order: paginator.ASC,
Expand All @@ -70,8 +87,6 @@ func NewPaginator(v interface{}, request map[string]interface{}) *Paginator {

p := paginator.New(opts...)

newInstance := &Paginator{Meta: PaginationMeta{}, Paginator: p}
newInstance.updateMeta(v, request)

newInstance := &Paginator{Meta: PaginationMeta{}, Paginator: p, model: v, filter: queryFilter}
return newInstance
}

0 comments on commit 4a5e055

Please sign in to comment.