我有一个显示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})
    }
}

类别:

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

产品:

type Products struct {
    gorm.Model
    CategoriesRefer   int64      `json:"cat_id" gorm:"column:cat_id"`
    Title             string     `json:"title" gorm:"column:title"`
    ...
}

推荐答案

您可以try custom preloading修改Preload函数加载Products的方式.代码应该如下所示:

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

Go相关问答推荐

[0]Func()as";请勿比较哨兵类型

为什么没有正确生成这些元组?

在 Go 中将元数据从一个 JPEG 复制到另一个

通过 Terraform 中的 MapNestedAtribute 进行迭代

是否需要手动调用rand.Seed?

Go Build删除信息

GORM中是否可能自动迁移具有循环关系的表?

Global Thread-local Storage 在 Go 中的可行性和最佳实践

这是实现超时的常见方法,为什么 time.After 不起作用

是否可以在调试期间在 VSCode 中预览 github.com/shopspring/decimal 值?

如何从 Asterisk Manager Interface Event 获取活动呼叫数

有没有办法计算枚举中定义的项目总数?

获取不带类型参数的泛型 struct 的类型名称

Golang Gin 绑定请求正文 XML 到 Slice

来自洪流公告的奇怪同行字段

如何使用 Go 获取 X11 中的窗口列表

在 connect-go 拦截器中修改响应体

如何使用带有Electron 表格 ID、Electron 表格名称、表格 ID 和值的 golang 在 googlesheet 中插入数据

不理解切片和指针

如何访问Go 1.18泛型 struct (structs)中的共享字段