[Go]GO語言實戰-開源WEB客服GO-FLY-gorm下分頁的實現

分頁功能幾乎是每一個項目裏都會使用的功能,在使用gorm的前提下,下面這樣實現分頁.前端

前端使用的是elementui , 只須要返回兩個參數就能夠前端分頁了 , 總頁數和每頁的條數git

後端須要知道兩個參數, 當前第幾頁和每頁的條數github

 

好比下面的代碼:後端

裏面的page是前端傳過來的 , pagesize是配置裏規定的, 就能夠交給gorm去分頁了ui

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裏面的代碼:spa

主要是offset 和 limit的使用code

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
}

效果是這樣的orm

 

 代碼就在下面的github裏面 blog

相關文章
相關標籤/搜索