Limit

Limit 指定要查询的最大记录数。

示例:

取出时间倒叙的最后5条记录

db.Order("created_at desc").Limit(5).Find(&users)

Offset

Offset指定开始返回记录前要跳过的记录数

offset 需要配合limit 使用

db.Limit(5).Offset(5).Order("created_at desc").Find(&users)

Count

获取模型的记录数。

注意:

使用count 不能用 Offset 或将Offset值设为 -1(-1代表取消offset限制)

否则会报 :sql: no rows in result set 的错误。

db.Limit(5).Offset(-1).Order("created_at desc").Find(&users).Count(&count)
 
// 或 
 
db.Model(&User{}).Where("name = ?", "jinzhu").Count(&count)

分页实例

示例1

package main
 
import (
	"fmt"
	"github.com/jinzhu/gorm"
	_ "github.com/jinzhu/gorm/dialects/mysql"
)
 
type User struct {
	gorm.Model
	Name string `gorm:"default:''"`
	IsMan bool `gorm:"not null;default:false"`
	Price *int `gorm:"default:0"`
}
 
 
func main() {
	db, err := gorm.Open("mysql", "root:root@/gormdb?charset=utf8&parseTime=True&loc=Local")
	defer db.Close()
	if err != nil {
		panic(err)
	}
 
	defer db.Close()
	//生成数据库表
	//db.AutoMigrate(&User{})
 
	//db.Create(&User{Name:"shijia1"})
 
	var users []User
 
	var page int = 2
	var pageSize int = 5
	var total int = 0
 
	// 获取取指page,指定pagesize的记录
	db.Where("price >= ?",0).Limit(pageSize).Offset((page-1)*pageSize).Order("created_at desc").Find(&users)
 
	// 获取总条数
	db.Model(&User{}).Where("price >= ?",0).Count(&total)
	fmt.Println(users,"总数:",total)
 
}
 

Limit 指定要查询的最大记录数。

 示例:

 取出时间倒叙的最后5条记录

示例2

models/problem_basic.go

package models

import (
	"gorm.io/gorm"
)

type ProblemBasic struct {
	gorm.Model
	Identity          string             `gorm:"column:identity;type:varchar(36);" json:"identity"` //问题表的唯一标识
	ProblemCategories []*ProblemCategory `gorm:"foreignKey:problem_id;references:id"`               //关联问题分类表
	Title             string             `gorm:"column:title;type:varchar(255);" json:"title"`      //文章标题
	Content           string             `gorm:"column:content;type:text;" json:"Content"`          //文章正文
	MaxRuntime        int                `gorm:"column:max_runtime;type:int"json:"max_runtime"`     //最大运行时间
	MaxMem            int                `gorm:"column:max_mem;type:int"json:"max_mem"`             //最大运行内存

}

func (table *ProblemBasic) Tablename() string {
	return "problem_basic"
}

func GetProblemList(keyword, categoryIdentity string) *gorm.DB {
	tx := Db.Model(new(ProblemBasic)).Preload("ProblemCategories").Preload("ProblemCategories.CategoryBasic").
		Where("title like ? OR content like ?", "%"+keyword+"%", "%"+keyword+"%")
	if categoryIdentity != "" {
		tx.Joins("RIGHT JOIN problem_category pc on pc.problem_id = problem_basic.id").
			Where("pc.category_id = (SELECT cb.id FROM category_basic cb.identity = ?)", categoryIdentity)
	}
	return tx
}

service/problem.go

import (
	"getcahrzp.cn/models"
	"github.com/gin-gonic/gin"
	"gorm.io/gorm"
	"log"
	"net/http"
	"strconv"
)

// GetProblemList
// @Tags 公共方法
// @Summary 问题列表
// @Param page query int false "请输入当前页,默认第一页"
// @Param size query int false "size"
// @Param keyword query string false "keyword"
// @Param category_identity query string false "category_identity"
// @Success 200 {string} json "{"code":"200","data":""}"
// @Router /problem-list [get]
func GetProblemList(c *gin.Context) {
	size, _ := strconv.Atoi(c.DefaultQuery("size", 20))
	page, err := strconv.Atoi(c.DefaultQuery("page",1))
	if err != nil {
		log.Println("GetProblemList Page strconv Error:", err)
		return
	}
	page = (page - 1) * size
	// page == 1 ==> offset 0

	var count int64
	keyword := c.Query("keyword")
	categoryIdentity := c.Query("category_identity")

	list := make([]*models.ProblemBasic, 0)
	tx := models.GetProblemList(keyword, categoryIdentity)
	err = tx.Count(&count).Offset(page).Limit(size).Find(&list).Error
	if err != nil {
		log.Println("Get Problem List Error:", err)
		return
	}

	c.JSON(http.StatusOK, gin.H{
		"code": 200,
		"data": map[string]interface{}{
			"list":  list,
			"count": count,
		},
	})
}