当前位置:网站首页>Starting from 3, add paging function in the business system

Starting from 3, add paging function in the business system

2022-06-23 15:03:00 Barry Yan

This section is relatively simple , The implementation of adding paging function makes use of gorm And synchronized changes Gin Receiving parameters of , And then realize the paging function .

Design logic

SQL grammar SELECT * FROM table LIMIT 10 OFFSET 5 , Just translate it from 5 Began to take 10 Data ,OFFSET It can be understood as skipping these lines and fetching data from behind ,LIMIT Just take a few lines of data .

So we have gorm You can use the encapsulated API, Such as Limit() and Offset() etc. , But you need two parameters , One is page Stands for page , The other is limit How many pieces of data per page , Next, write the code .

Let's take a look at the modified code

dao Layer implementation method :

......

func (impl CountNumDAOImpl) FindAllNumInfo(ctx context.Context, page int, limit int) []entity.NumInfo {
    
   var infos []entity.NumInfo
   if page <= 0 || limit <= 0 {
    
      impl.db.Find(&infos)
   } else {
    
      impl.db.Limit(limit).Offset((page - 1) * limit).Find(&infos)
   }
   return infos
}

......

controller Layer interface :

......

func (impl NumInfoControllerImpl) FindAll(c *gin.Context) {
    
   page := c.Query("page")
   limit := c.Query("limit")
   numInfos := impl.dao.FindAllNumInfo(c, cast.ToInt(page), cast.ToInt(limit))
   c.JSON(200, map[string]interface{
    }{
    "code": 0, "msg": "", "count": len(numInfos), "data": numInfos})
}

......

test :
 Insert picture description here
Results after paging :
 Insert picture description here

原网站

版权声明
本文为[Barry Yan]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/174/202206231400369126.html