使用 Gorm 实现分页功能
-
工具函数
我们首先定义一个通用的 Paging 函数和结构体,用于处理分页逻辑: -
type PagingParams struct { Page int `json:"page"` Limit int `json:"limit"` } type PagingResponse struct { Total int64 List interface{} }
-
// Paging 分页 page=0时查询全部 func Paging(model interface{}, sql *gorm.DB, pagingParams models.PagingParams) (models.PagingResponse, error) { var total int64 if err := sql.Count(&total).Error; err != nil { return models.PagingResponse{}, err } if pagingParams.Page == 0 { sql.Find(&model) if isEmpty(model) { model = []interface{}{} } res := models.PagingResponse{ Total: total, List: model, } return res, nil } if err := sql.Limit(pagingParams.Limit).Offset((pagingParams.Page - 1) * pagingParams.Limit).Find(&model).Error; err != nil { return models.PagingResponse{}, err } if isEmpty(model) { model = []interface{}{} } res := models.PagingResponse{ Total: total, List: model, } return res, nil }
-
结构体与使用方法
接下来,我们定义一个获取分类的接口,示例代码如下:
type GetRecordsRequest struct { models.PagingParams ID uint `json:"id"` UserID uint `json:"userId"` //用户ID 管理员可以查询 CategoryID uint `json:"categoryId"` //分类ID Keyword string `json:"keyword"` //关键字 Date time.Time `json:"date"` //时间 } // GetRecords 获取记录 // // @Summary 获取记录 // @Tags 记录 // @Accept json // @Produce json // @Param body body GetRecordsRequest true "Request body" // @Success 200 {object} models.PagingResponse // @Router /api/v1/record/GetRecords [post] func GetRecords(c *gin.Context) { var req GetRecordsRequest if err := c.ShouldBindJSON(&req); err != nil { response.FailWithInvalidArgs(c, err.Error()) return } sql := core.DB.Where("user_id = ?", utils.GetUserID(c)) if req.ID != 0 { sql = sql.Where("id = ?", req.ID) } if req.UserID != 0 { sql = sql.Where("user_id = ?", req.UserID) } if req.CategoryID != 0 { sql = sql.Where("category_id = ?", req.CategoryID) } if req.Keyword != "" { sql = sql.Where("name LIKE ? OR description LIKE ?", "%"+req.Keyword+"%", "%"+req.Keyword+"%") } res, err := utils.Paging(models.Record{}, sql, req.PagingParams) if err != nil { response.FailWithData(c, err.Error()) return } response.OkWithData(c, res) }