Gorm

发布时间 2023-11-12 22:54:56作者: PEAR2020

1. use pagination to query + count total 

    global.DB.Scopes(Paginate(int(req.Pages), int(req.PagePerNums))).Find(&brands)

    // total
    var total int64 global.DB.Model(&model.Brands{}).Count(&total)
    brandListResponse.Total = int32(total)
func Paginate(pg, pgSize int) func(db *gorm.DB) *gorm.DB {
    return func(db *gorm.DB) *gorm.DB {
        switch {
        case pgSize > 100:
            pgSize = 100
        case pgSize <= 0:
            pgSize = 10
        }
        offset := (pg - 1) * pgSize
        return db.Offset(offset).Limit(pgSize)
    }
}