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"`
...
}
CodePudding user response:
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})
}
}