英文:
How to get updated output using raw sql builder in gorm
问题
我正在尝试将更新后的帖子放入下面的函数中的结构体中:
func UpdatePost(c *gin.Context) {
id := c.Param("id")
var body struct {
Title string
PostText string
Img string
}
c.Bind(&body)
var post models.Post
initializers.DB.Raw("UPDATE posts SET title = ?, post_text = ?, img = ? WHERE id = ?", body.Title, body.PostText, body.Img, id).Scan(&post)
c.JSON(http.StatusOK, gin.H{
"post": post,
})
}
我的帖子在数据库中成功更新了,但是即使使用了Scan()
函数,我的结构体看起来像这样:
"post": {
"ID": 0,
"title": "",
"postText": "",
"img": "",
"userName": "",
"likedBy": null,
"createdBy": 0,
}
这里该怎么办呢?
英文:
I'm trying to get my updated post in to a struct in the below function
func UpdatePost(c *gin.Context) {
id := c.Param("id")
var body struct {
Title string
PostText string
Img string
}
c.Bind(&body)
var post models.Post
initializers.DB.Raw("UPDATE posts SET title = ?, post_text = ?, img = ? WHERE id = ?", body.Title, body.PostText, body.Img, id).Scan(&post)
c.JSON(http.StatusOK, gin.H{
"post": post,
})
}
My Post is being successfully updated in DB but
even after using Scan(), my struct looks like this
"post": {
"ID": 0,
"title": "",
"postText": "",
"img": "",
"userName": "",
"likedBy": null,
"createdBy": 0,
}
What's the way to go here?
答案1
得分: 0
刚刚错过了在 WHERE id = ? 后面添加 RETURNING * 的部分,就像 @rahmat 评论中提到的那样。将此留在这里,供将来尝试查找 gorm 原始 SQL 构建器的正确语法的人参考。
英文:
Just Missed RETURNING * after WHERE id = ? like @rahmat commented. Leaving this here for anyone who's trying to find the correct syntax for gorm raw SQL builder in future
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论