You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Gin-Gorm中查询分类时如何预加载每个分类的前5个关联产品?

问题:预加载分类时仅获取每个分类下的5个产品

我有一个展示Categories(分类)的函数,想要使用Preload方法同时展示与该分类关联的Products(产品),但不需要所有产品,仅需每个分类下的5个,请问该如何修改查询语句?

原函数代码

func GetAllCategories(c *gin.Context) {
    Categories := []models.Categories{}
    if err := config.DB.Preload("Products").Find(&Categories).Error; err != nil {  
        c.JSON(http.StatusInternalServerError, err.Error())
    } else {
        c.JSON(http.StatusOK, gin.H{"data": &Categories})
    }
}

原结构体定义

Categories 结构体

type Categories struct {
    ID         uint       `json:"ID" gorm:"primaryKey"`
    Title      string     `json:"title"`
    // 其他字段...
    Products   []Products `gorm:"foreignKey:CategoriesRefer" json:"products"`
}

Products 结构体

type Products struct {
    gorm.Model
    CategoriesRefer   int64      `json:"cat_id" gorm:"column:cat_id"`
    Title             string     `json:"title" gorm:"column:title"`
    // 其他字段...
}

解决方案

GORM的Preload方法支持传入自定义查询条件,给Preload添加第二个参数,通过匿名函数限制每个分类下产品的数量即可。

修改后的函数代码

func GetAllCategories(c *gin.Context) {
    Categories := []models.Categories{}
    // 在Preload中添加Limit(5)的自定义查询
    if err := config.DB.Preload("Products", func(db *gorm.DB) *gorm.DB {
        return db.Limit(5)
    }).Find(&Categories).Error; err != nil {  
        c.JSON(http.StatusInternalServerError, err.Error())
    } else {
        c.JSON(http.StatusOK, gin.H{"data": &Categories})
    }
}

补充说明

  • 上述代码会让每个分类仅预加载最多5个关联产品;如果需要按特定规则筛选(比如取最新的5个),可以在回调函数中补充排序条件,示例:
    return db.Order("created_at DESC").Limit(5)
    

内容的提问来源于stack exchange,提问作者Casper

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.25 21:27:27