go - 返回正确的列数,但所有行都是空的
问题描述
我正在尝试使用 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 有一个table
with 列id
作为 primary_key
我得到的结果是一个大小正确的表,但所有行都是空的......
....[{} {} {} {} {} {} {} {} {} {} {} {} {} {} {} {} {} {} {} {} {} {} {} {} {} {} {} {} {} {} {} {} {} {} {} {} {} {} {} {} {} {} {} {} {} {} {} {} {} {} {} {} {} {} {} {} {} {} {} {} {} {} {} {} {} {} {} {} {} {} {} {} {} {} {} {} {} {} {} {} {} {} {} {} {} {} {} {} {} {} {} {} {} {} {} {} {} {} {} {} {} {} {} {} {} {} {} {} {} {} {} {} {} {} {} {} {} {} {} {} {} {}
{} {} {} {} {} {} {} {} {} {} {} {} {} {} {} {} {} {} {} {} {} {} {} {} {} {} {} {} {} {} {} {} {} {} {} {} {} {} {} {} {} {} {} {} {} {} {} {} {} {} {} {} {} {} {} {} {} {} {} {} {} {} {} {} {} {} {} {} {} {} {} {} {} {} {} {} {} {} {} {} {} {} {} {} {} {} {} {} {} {} {} {} {} {} {} {} {} {} {} {} {} {} {} {} {} {} {} {} {} {} {} {} {} {} {} {} {} {} {} {} {} {} {} {}
{} {} {} {} {} {} {} {} {} {} {} {} {} {} {} {} {} {} {} {} {} {}]
但是总行数是正确的len(t) = 20523
我认为我做错的是在 的定义中Table struct
,也许我错误地指定了 Id 列的名称?任何建议表示赞赏。
解决方案
您可以使用 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)")
}
希望这对你有帮助
推荐阅读
- reactjs - 存储下拉选择并从 localStorage 加载它
- ios - 将数据从 UIViewControllerRepresentable 传递给 SwiftUI
- ruby-on-rails - 在 Rails 中加入两个表,被称为 has_one: ".. ",class_name:"..."
- macos - 在 Mac 上按名称删除嵌套子目录?
- django - Django 视图和模板以及静态 html
- python - Pandas、Numpy、合并多列并消除空值
- r - R如何从正交lm构造形式为c0 + c1 * x + .. + cn * x^n的多项式(使用poly(raw = F))
- c# - 在 Func 中封装异步方法
- javascript - 如何在棋盘上确定玩家的视野
- php - Laravel 绑定解析异常。目标类不存在