gogo-gormbelongs-to

How to create BelongTo relationship in gorm (GoLang)


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)