首页 > 解决方案 > 返回正确的列数,但所有行都是空的

问题描述

我正在尝试使用 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 有一个tablewith 列id作为 primary_key

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

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

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

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

标签: gogo-gorm

解决方案


您可以使用 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)")
}

希望这对你有帮助


推荐阅读