[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里面 

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM