英文:
Why is the value of my database column always 0?
问题
我正在使用go-gorm从PostgreSQL数据库中获取值。相关的代码如下所示:
type Chip struct {
UUID string `db:"uuid"`
URL string `db:"url"`
N int `db:"n"`
Pack_ID int `db:"pack_id"`
}
func getChip(uuid string) (Chip, error) {
var c Chip
err := DB.Model(Chip{}).Where("uuid = ?", uuid).First(&c)
return c, err.Error
}
当我将UUID字符串传递给getChip
函数时,返回的行是正确的,所有的值都是正确的,除了c.Pack_ID
始终为0
。顺便说一下,从未出现过Pack_ID
为0
的行。
这是来自pgAdminIII的屏幕截图,希望能解决问题:
有什么想法可能出了什么问题吗?我完全不知所措...
英文:
I'm using go-gorm to fetch values from a PostgreSQL database. The relevant code is shown below:
type Chip struct {
UUID string `db:uuid`
URL string `db:url`
N int `db:n`
Pack_ID int `db:pack_id`
}
func getChip(uuid string) (Chip, error) {
var c Chip
err := DB.Model(Chip{}).Where("uuid = ?", uuid).First(&c)
return c, err.Error
}
When I pass a UUID string to getChip
, the correct row is returned and all values are correct except for c.Pack_ID
, which is always 0
. Incidentally there is never a row for which Pack_ID
is 0
.
Here is a screenshot from pgAdminIII, which I hope will shed some light on the problem:
Any ideas as to what might be going wrong? I'm at a complete loss, here...
答案1
得分: 5
你正在使用的结构标签似乎格式不正确。结构标签应该是以下形式:
name:"value"
但你的标签中缺少了值周围的引号:
name:value
请尝试进行修正。否则,Go中的结构标签解析器将无法工作,因为它依赖于这些引号,可以在结构标签解析器的实现中看到。
关于特定的结构标签:你确定应该使用db
吗?根据Gorm文档,你可能想使用gorm:"column:..."
。我原本期望你的类型定义是:
type Chip struct {
UUID string `gorm:"column:uuid;primary_key"`
URL string `gorm:"column:url"`
N int `gorm:"column:n"`
Pack_ID int `gorm:"column:pack_id"`
}
英文:
The struct tags you're using appear to be malformed. A struct tag should be of the form:
name:"value"
but what you've got is missing the quotes around the value:
name:value
Try correcting this. Otherwise, the struct tag parser in Go has no chance to work, as it depends on those quotes, as seen in the struct tag parser implementation.
With regards to specific struct tags: are you sure you're supposed to use db
? According to the Gorm documentation, you probably want to use gorm:"column:..."
. I was expecting your type definition to be:
type Chip struct {
UUID string `gorm:"column:uuid;primary_key"`
URL string `gorm:"column:url"`
N int `gorm:"column:n"`
Pack_ID int `gorm:"column:pack_id"`
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论