英文:
query for maximum value in row returns "0" in GoRM
问题
使用GoRM与MySQL数据库,我在从一个相当简单的查询中返回数据时遇到了问题。
var newPrsPk struct {
presentation_pk int `gorm:"column:presentation_pk"`
}
db.Raw("select max(presentation_pk) as presentation_pk from presentation").Scan(&newPrsPk)
log.Println(newPrsPk)
log.Println(newPrsPk.presentation_pk)
结果如下所示:
[2023-06-16 09:53:27] [43.29ms] select max(presentation_pk) as presentation_pk from presentation
[1 rows affected or returned ]
2023/06/16 09:53:27 {0}
2023/06/16 09:53:27 0
但是0绝对不是该列的最大值,在MySQL Workbench中运行查询返回了正确的值,所以我必须假设我写错了什么。
GoRM的文档不是很好,但这是一个非常直接的查询,所以我感到困惑。
"presentation_pk"是我的表中一个自增的int字段,这个查询紧随一个GoRM的Create()函数之后(因为似乎没有办法从MySQL中返回一个自增的字段)。鉴于我看不到任何明确的"commit"函数,我假设GoRM会自动提交更改,而这不是一个并发问题。
任何帮助将不胜感激。
英文:
Using GoRM with a mySQL database, i'm having trouble returning data from a fairly simple query.
var newPrsPk struct {
presentation_pk int `gorm:"column:presentation_pk"`
}
db.Raw("select max(presentation_pk) as presentation_pk from presentation").Scan(&newPrsPk)
log.Println(newPrsPk)
log.Println(newPrsPk.presentation_pk)
which results in the following output:
[2023-06-16 09:53:27] [43.29ms] select max(presentation_pk) as presentation_pk from presentation
[1 rows affected or returned ]
2023/06/16 09:53:27 {0}
2023/06/16 09:53:27 0
But 0 is definitely not the max value for that column, and running the query in mySQL workbench returns the appropriate value, so I have to assume there's something wrong with how i'm writing this.
GoRM's documentation isn't amazing, but this is a pretty straightforward query, so i'm flummoxed.
"presentation_pk" is an auto-incrementing int field in my table, and this query immediately follows a GoRM Create() function (since there doesn't seem to be a way to return an auto-incremented field from mySQL). given that there's no kind of explicit "commit" function that I can see, I'm assuming GoRM automatically commits changes, and that this isn't a concurrency issue.
Any help would be appreciated.
答案1
得分: 2
在使用Gorm时,你的结构体变量需要使用PascalCase而不是snake case。请查看这里的约定规范文档,然后你可以了解有关声明模型的信息。
如果你将你的结构体更改为以下形式:
var result struct {
PresentationPK int `gorm:"column:presentation_pk"`
}
那么你的查询应该可以工作了,然后你可以使用PresentationPK
打印出结果。
英文:
When working with Gorm your struct variables need to be PascalCase not snake case. Take a look at the conventions document here and then you can see about Declaring Models here.
If you change your struct to be something like this:
var result struct {
PresentationPK int `gorm:"column:presentation_pk"`
}
Then your query should work, and then you can print out your results using PresentationPK
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论