在GoRM中,查询行中的最大值返回”0″。

huangapple go评论89阅读模式
英文:

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

huangapple
  • 本文由 发表于 2023年6月16日 23:34:28
  • 转载请务必保留本文链接:https://go.coder-hub.com/76491655.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定