How to get field value in GORM

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

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)

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:

确定