PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Sunday, October 23, 2022

[FIXED] How to get updated output using raw sql builder in gorm

 October 23, 2022     go, go-gorm, postgresql, sql, sql-update     No comments   

Issue

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?


Solution

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



Answered By - Athfan
Answer Checked By - Mildred Charles (PHPFixing Admin)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing