如何在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
相关产品推荐
相关产品推荐

