英文:
How to select first N elements Gin-Gorm
问题
我有一个显示Categories
的函数,我想使用Preload
方法来显示与该类别相关的Products
,但我只需要5个产品,该如何修改请求?
函数:
func GetAllCategories(c *gin.Context) {
Categories := []models.Categories{}
if err := config.DB.Preload("Products").Limit(5).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"`
...
}
英文:
I have a function that displays Categories
, I want to use the Preload
method to also display Products
related to this category, but I don’t need all the products, but only 5 pieces, how can I fix the request?
Function:
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"`
...
}
答案1
得分: 1
你可以尝试使用自定义预加载(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})
}
}
你可以参考GORM文档了解更多关于自定义预加载的信息。
英文:
You can try custom preloading to modify how the Preload
function is going to load Products
. The code should look something like this:
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})
}
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论