英文:
How to get field value in GORM
问题
我有一个函数,它将所有的Product
数据输出到data数组
,但我还需要在relatives数组
中显示相同category
的5个产品。
函数:
func GetProductsById(c *gin.Context) {
var Product models.Products
Products := []models.Products{}
config.DB.Where("cat_id", func(tx *gorm.DB) *gorm.DB {
return config.DB.Where("id=?", c.Query("prod_id")).Select("cat_id").First(&Product)
}).Find(&Products)
if err := config.DB.Where("id=?", c.Query("prod_id")).First(&Product).Error; err != nil {
c.JSON(http.StatusInternalServerError, err.Error())
} else {
c.JSON(http.StatusOK, gin.H{
"data": []models.Products{Product},
"relatives": &Products})
}
}
我尝试自己做,但我无法从数据数组中访问product category
来显示5个相似的产品。
并且我遇到了错误:
cannot convert 0xa182e0 to Int8
英文:
I have a function that outputs all Product
data to the data array
, but I also need to display 5 products from the same category
in the relatives array
.
Function:
func GetProductsById(c *gin.Context) {
var Product models.Products
Products := []models.Products{}
config.DB.Where("cat_id", func(tx *gorm.DB) *gorm.DB {
return config.DB.Where("id=?", c.Query("prod_id")).Select("cat_id").First(&Product)
}).Find(&Products)
if err := config.DB.Where("id=?", c.Query("prod_id")).First(&Product).Error; err != nil {
c.JSON(http.StatusInternalServerError, err.Error())
} else {
c.JSON(http.StatusOK, gin.H{
"data": []models.Products{Product},
"relatives": &Products})
}
}
I tried to do it myself, but I can't access the product category
from the data array to show 5 similar products.
And i have error:
cannot convert 0xa182e0 to Int8
答案1
得分: 1
我认为你的ID是整数,而c.Query("prod_id")返回的是字符串。你需要将它转换为整数:
intVar, err := strconv.Atoi(c.Query("prod_id"))
如果代码没有错误:
config.DB.Where("cat_id", func(tx *gorm.DB) *gorm.DB {
return config.DB.Where("id=?", intVar).Select("cat_id").First(&Product)
}).Find(&Products)
英文:
i think your id is integer, and c.Query("prod_id") returns string. you must be cast it to integer by
intVar, err := strconv.Atoi(c.Query("prod_id"))
if code has not error:
config.DB.Where("cat_id", func(tx *gorm.DB) *gorm.DB {
return config.DB.Where("id=?", intVar).Select("cat_id").First(&Product)
}).Find(&Products)
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论