如何使用 GORM 中的原始 SQL 构建器获取更新后的输出。

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

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

huangapple
  • 本文由 发表于 2022年8月14日 09:22:48
  • 转载请务必保留本文链接:https://go.coder-hub.com/73348591.html
匿名

发表评论

匿名网友

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

确定