从gorm数据库返回nil的函数,它返回结构体列表。

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

Function which returns list of struct from gorm database returning nil?

问题

我正在尝试创建一个函数,该函数将以结构体的切片形式输出表中的所有内容。

  1. func FetchAll(parameter interface{}) []interface{} {
  2. var model interface{}
  3. var resultArray []interface{}
  4. db := common.GetDB()
  5. rows, err := db.Model(parameter).Where(parameter).Rows()
  6. if err != nil {
  7. fmt.Print(err.Error())
  8. return nil
  9. }
  10. for rows.Next() {
  11. db.ScanRows(rows, &model)
  12. resultArray = append(resultArray, model)
  13. }
  14. fmt.Println(resultArray)
  15. return resultArray
  16. }

用法:

  1. c.JSON(200, FetchAll(&ProductImage{ProductID: productID}))

但输出结果如下:

  1. [<nil>,<nil>,<nil>]

为什么会这样呢?

英文:

I'm trying to make a function that will output all of the contents from a table as a slice of the struct the table is.

  1. func FetchAll(parameter interface{}) []interface{} {
  2. var model interface{}
  3. var resultArray []interface{}
  4. db := common.GetDB()
  5. rows, err := db.Model(parameter).Where(parameter).Rows()
  6. if err != nil {
  7. fmt.Print(err.Error())
  8. return nil
  9. }
  10. for rows.Next() {
  11. db.ScanRows(rows, &amp;model)
  12. resultArray = append(resultArray, model)
  13. }
  14. fmt.Println(resultArray)
  15. return resultArray
  16. }

Usage:

  1. c.JSON(200, FetchAll(&amp;ProductImage{ProductID: productID}))

But the output is the following:

  1. [&lt;nil&gt;,&lt;nil&gt;,&lt;nil&gt;]

Why is it?

答案1

得分: 1

model的类型不能是interface{}

你可以使用var model = map[string]interface{}{}

更简单的写法:

  1. func FetchAll(parameter interface{}) []map[string]interface{} {
  2. var resultArray []map[string]interface{}
  3. db := common.GetDB()
  4. err := db.Model(parameter).Where(parameter).Find(&resultArray).Error
  5. if err != nil {
  6. fmt.Print(err)
  7. return nil
  8. }
  9. fmt.Println(resultArray)
  10. return resultArray
  11. }
英文:

the type of model can't be interface{}

you can use var model = map[string]interface{}{}

Easier to write:

  1. func FetchAll(parameter interface{}) []map[string]interface{} {
  2. var resultArray []map[string]interface{}
  3. db := common.GetDB()
  4. err := db.Model(parameter).Where(parameter).Find(&amp;resultArray).Error
  5. if err != nil {
  6. fmt.Print(err)
  7. return nil
  8. }
  9. fmt.Println(resultArray)
  10. return resultArray
  11. }

huangapple
  • 本文由 发表于 2021年8月9日 20:11:00
  • 转载请务必保留本文链接:https://go.coder-hub.com/68711856.html
匿名

发表评论

匿名网友

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

确定