【问题标题】:Returning the right number of columns, but all rows are empty返回正确的列数,但所有行都是空的
【发布时间】:2020-02-19 05:31:11
【问题描述】:

我正在尝试使用 Gorm 从 mysql 进行简单的读取。

type Table struct {
    Id string `json:"Id" db:"Id" column:"Id" gorm:"column:Id"`
}


func getTable(w http.ResponseWriter, r *http.Request) {
    t:= []Table{}
    db.Debug().Table("Table").Find(&t)
    fmt.Println(table)
    fmt.Println("len(table)")
}

MySql 有一个 tableid 作为主键

我得到的结果是一个大小正确的表格,但所有行都是空的......

....[{} {} {} {} {} {} {} {} {} {} {} {} {} {} {} {} {} {} {} {} {} {} {} {} {} {} {} {} {} {} {} {} {} {} {} {} {} {} {} {} {} {} {} {} {} {} {} {} {} {} {} {} {} {} {} {} {} {} {} {} {} {} {} {} {} {} {} {} {} {} {} {} {} {} {} {} {} {} {} {} {} {} {} {} {} {} {} {} {} {} {} {} {} {} {} {} {} {} {} {} {} {} {} {} {} {} {} {} {} {} {} {} {} {} {} {} {} {} {} {} {} {} {} {} {} {} {} {} {} {} {} {} {} {} {} {} {} {} {} {} {} {} {} {} {} {} {} {} {} {} {} {} {} {} {} {} {} {} {} {} {} {} {} {} {} {} {} {} {} {} {} {} {} {} {} {} {} {} {} {} {} {} {} {} {} {} {} {} {} {} {} {} {} {} {} {} {} {} {} {} {} {} {} {} {} {} {} {} {} {} {} {} {} {} {} {} {} {} {} {} {} {} {} {} {} {} {} {} {} {} {} {} {} {} {} {} {} {} {} {} {} {} {} {} {} {} {} {} {} {} {} {} {} {} {} {} {} {} {} {} {} {} {} {} {} {} {} {}]

但是总行数是正确的len(t) = 20523

我认为我做错了在Table struct 的定义中,也许我错误地指定了Id 列的名称?任何建议表示赞赏。

【问题讨论】:

  • 您的 gorm 标签看起来不正确。这有帮助吗? gorm.io/docs/models.html
  • Gorm 怎么知道如何将MySql 映射到我的Table struct
  • 我试过Id string json:"Id" db:"Id" column:"Id" gorm:"type:varchar(20)"`` 还是一样的

标签: go go-gorm


【解决方案1】:

您可以使用 db.Raw 并检查字段的名称为“Id”,如下所示:

type Table struct {
	Id string `json:"Id" db:"Id" column:"Id" gorm:"column:Id"`
}

func getTable() {
	t := []Table{}
	db := config.ConnectDB()
	defer db.Close()

	db.Raw(" SELECT idEvaluacionAnual as Id FROM EvaluacionesAnuales ").Scan(&t)
	fmt.Println(t.Id)
	fmt.Println("len(table)")
}

希望对你有帮助

【讨论】:

  • 先生,我不想在 Gorm 中使用 Raw Sql。在这种情况下,我可能根本不使用Gorm
  • 你说你的Sql表有字段id,那么你需要在gorm中变量的元数据中指定名称:gorm:"column:id" 小写
  • 你是小写的吗?
  • 我的列名是adId,所以我使用了驼峰格式的gorm:"column:adId"
  • type Kijiji struct { AdId 字符串 json:"adId" db:"adId" gorm:"column:adId" gorm:"type:varchar(20)"` } `它必须是这样的
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-08-09
  • 1970-01-01
  • 2015-08-23
  • 2020-08-04
  • 1970-01-01
相关资源
最近更新 更多