You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在GORM中使用Raw SQL Builder获取更新后的结果?

问题原因

普通的UPDATE SQL语句执行后不会返回更新后的行数据,因此你调用Scan(&post)无法获取到更新后的内容,只能得到零值初始化的结构体。

解决方案

方案一:使用GORM原生更新方法(推荐)

这种方式更贴合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
    // 先查询目标帖子
    if err := initializers.DB.First(&post, id).Error; err != nil {
        c.JSON(http.StatusNotFound, gin.H{"error": "帖子不存在"})
        return
    }

    // 更新结构体字段
    post.Title = body.Title
    post.PostText = body.PostText
    post.Img = body.Img

    // 保存更新
    if err := initializers.DB.Save(&post).Error; err != nil {
        c.JSON(http.StatusInternalServerError, gin.H{"error": "更新帖子失败"})
        return
    }

    c.JSON(http.StatusOK, gin.H{
        "post": post,
    })
}

方案二:使用Raw SQL并让数据库返回更新行

如果坚持用原生SQL,需要根据数据库类型调整语句:

  • PostgreSQL:支持RETURNING子句直接返回更新后的行
initializers.DB.Raw("UPDATE posts SET title = ?, post_text = ?, img = ? WHERE id = ? RETURNING *", body.Title, body.PostText, body.Img, id).Scan(&post)
  • MySQL:不支持RETURNING,需先执行更新再查询
// 执行更新操作
initializers.DB.Exec("UPDATE posts SET title = ?, post_text = ?, img = ? WHERE id = ?", body.Title, body.PostText, body.Img, id)
// 查询更新后的帖子
initializers.DB.First(&post, id)

内容的提问来源于stack exchange,提问作者user17402771

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.22 10:57:41