PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0
Showing posts with label go-gorm. Show all posts
Showing posts with label go-gorm. Show all posts

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)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

Tuesday, July 26, 2022

[FIXED] How to create BelongTo relationship in gorm (GoLang)

 July 26, 2022     belongs-to, go, go-gorm     No comments   

Issue

Here is my Struct

type Book struct {
    ID        uint `json:"id" gorm:"primary_key"`
    Yearmonth      string `json:"yearmonth"`
    Realname      string `json:"real_name"`
    LanguageId int
    Language   Language
}

and here is my Controller Logic

func GetBooks(c *gin.Context)  {
  db := c.MustGet("db").(*gorm.DB)

  var language []models.Language
  if err := db.Where("id=?", c.Param("language_id")).First(&language).Error;

  err != nil {
      c.JSON(http.StatusBadRequest, gin.H{"data": "No Records Found"})
      return
  }

  var books []models.Book
  if errBooks := db.Where("language_id=?", c.Param("language_id")).Find(&books).Error;

  errBooks != nil {
      c.JSON(http.StatusBadRequest, gin.H{"data": "No Books Found"})
      return
  }

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

I tried in a couple of ways somehow I'm getting empty data as result. Any suggestions or help that would great. TIA


Solution

The problem is language_id is not parsed from URL. .Param() used to get parameter in path. Ex:

router.GET("/user/:id", func(c *gin.Context) {
    // a GET request to /user/john
    id := c.Param("id") // id == "john"
})

But you are not specify any path param. You are passing language_id as query param in URL. So, to get querystring parameters you need to use .Query(). Ex:

GET /path?id=1234&name=Manu&value=
   c.Query("id") == "1234"
   c.Query("name") == "Manu"
   c.Query("value") == ""
   c.Query("wtf") == ""

So, use c.Query("language_id") instead of c.Param("language_id")

db.Where("id=?", c.Query("language_id")).First(&language)
db.Where("language_id=?", c.Query("language_id")).Find(&books)


Answered By - Eklavya
Answer Checked By - Timothy Miller (PHPFixing Admin)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

Sunday, July 24, 2022

[FIXED] How to specify path to gorm structure file

 July 24, 2022     go-gin, go-gorm, json     No comments   

Issue

I have a Products structure:

type Products struct {
    gorm.Model
    CategoriesRefer   int64      `json:"cat_id" gorm:"column:cat_id"`
    Title             string     `json:"title" gorm:"column:title"`
    ...
    Image             string     `json:"image" gorm:"column:image"`
}

The JSON request will contain the path to the image, which is stored in another folder of my project(not in db folder), how can I specify this in the structure?


Solution

I believe something like this should work.

package main

import (
    "fmt"
    "os"
    "path/filepath"
)

func main() {
    ex, err := os.Executable()
    if err != nil {
        panic(err)
    }
    exPath := filepath.Dir(ex)
    imagePath := fmt.Sprintf("%s/../photos", exPath) // change photos to correct directory name
    fmt.Println("imagePath:", imagePath)
}

However as mentioned in comments this isn't a great idea as it will be relative to the directory where the compiled binary executable is located. You may want to use something like an Environment Variable to control this directory. That way way you can set it to different directories for testing, development, production, etc...



Answered By - Pitchinnate
Answer Checked By - Timothy Miller (PHPFixing Admin)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Older Posts Home
View mobile version

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
All Comments
Atom
All Comments

Copyright © PHPFixing