[Go]GO语言实战-开源WEB客服GO-FLY-gorm下分页的实现

分页功能几乎是每个项目里都会使用的功能,在使用gorm的前提下,下面这样实现分页.

前端使用的是elementui , 只需要返回两个参数就可以前端分页了 , 总页数和每页的条数

后端需要知道两个参数, 当前第几页和每页的条数

 

比如下面的代码:

里面的page是前端传过来的 , pagesize是配置里规定的, 就可以交给gorm去分页了

func GetVisitors(c *gin.Context) {
    page,_:=strconv.Atoi(c.Query("page"))
    kefuId,_:=c.Get("kefu_name")
    vistors:=models.FindVisitorsByKefuId(uint(page),config.VisitorPageSize,kefuId.(string))
    count:=models.CountVisitorsByKefuId(kefuId.(string))
    c.JSON(200, gin.H{
        "code": 200,
        "msg":  "ok",
        "result":gin.H{
            "list":vistors,
            "count":count,
            "pagesize":config.PageSize,
        },
    })
}

 

gorm里面的代码:

主要是offset 和 limit的使用

func FindVisitorsByKefuId(page uint,pagesize uint,kefuId string)[]Visitor{
    offset:=(page-1)*pagesize
    if offset<0{
        offset=0
    }
    var visitors []Visitor
    DB.Where("to_id=?",kefuId).Offset(offset).Limit(pagesize).Order("status desc, updated_at desc").Find(&visitors)
    return visitors
}

效果是这样的

 

 代码就在下面的github里面 

 

posted @ 2020-09-11 11:55  唯一客服系统开发笔记  阅读(732)  评论(0编辑  收藏  举报