How to get field value in GORM

huangapple go评论110阅读模式
英文:

How to get field value in GORM

问题

我有一个函数,它将所有的Product数据输出到data数组,但我还需要在relatives数组中显示相同category的5个产品。

函数:

  1. func GetProductsById(c *gin.Context) {
  2. var Product models.Products
  3. Products := []models.Products{}
  4. config.DB.Where("cat_id", func(tx *gorm.DB) *gorm.DB {
  5. return config.DB.Where("id=?", c.Query("prod_id")).Select("cat_id").First(&Product)
  6. }).Find(&Products)
  7. if err := config.DB.Where("id=?", c.Query("prod_id")).First(&Product).Error; err != nil {
  8. c.JSON(http.StatusInternalServerError, err.Error())
  9. } else {
  10. c.JSON(http.StatusOK, gin.H{
  11. "data": []models.Products{Product},
  12. "relatives": &Products})
  13. }
  14. }

我尝试自己做,但我无法从数据数组中访问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:

  1. func GetProductsById(c *gin.Context) {
  2. var Product models.Products
  3. Products := []models.Products{}
  4. config.DB.Where("cat_id", func(tx *gorm.DB) *gorm.DB {
  5. return config.DB.Where("id=?", c.Query("prod_id")).Select("cat_id").First(&Product)
  6. }).Find(&Products)
  7. if err := config.DB.Where("id=?", c.Query("prod_id")).First(&Product).Error; err != nil {
  8. c.JSON(http.StatusInternalServerError, err.Error())
  9. } else {
  10. c.JSON(http.StatusOK, gin.H{
  11. "data": []models.Products{Product},
  12. "relatives": &Products})
  13. }
  14. }

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")返回的是字符串。你需要将它转换为整数:

  1. intVar, err := strconv.Atoi(c.Query("prod_id"))

如果代码没有错误:

  1. config.DB.Where("cat_id", func(tx *gorm.DB) *gorm.DB {
  2. return config.DB.Where("id=?", intVar).Select("cat_id").First(&Product)
  3. }).Find(&Products)
英文:

i think your id is integer, and c.Query("prod_id") returns string. you must be cast it to integer by

  1. intVar, err := strconv.Atoi(c.Query("prod_id"))

if code has not error:

  1. config.DB.Where("cat_id", func(tx *gorm.DB) *gorm.DB {
  2. return config.DB.Where("id=?", intVar).Select("cat_id").First(&Product)
  3. }).Find(&Products)

huangapple
  • 本文由 发表于 2022年7月17日 18:00:36
  • 转载请务必保留本文链接:https://go.coder-hub.com/73010851.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定