K
K
kireke2021-08-16 19:33:51
go
kireke, 2021-08-16 19:33:51

How to update fields in db that are not empty string go gorm?

Please tell me, I have a function to update the value of those fields in the database that came from the frontend and which are not an empty string

func EditProduct(c *gin.Context) {
  id := c.Params.ByName("id")
  var body ProductReq
  var product models.Product
  if err := c.ShouldBindJSON(&body); err != nil {
    log.Fatal(err.Error())
    return
  }
  database.DB.Where("id = ?", id).First(&product)
  if body.Title != "" {
    product.Title = body.Title
  }
  if body.Type != "" {
    product.Type = body.Type
  }
  if body.Img != "" {
    product.Img = body.Img
  }
  if body.Brand != "" {
    product.Brand = body.Brand
  }
  if body.Price != "" {
    product.Price = body.Price
  }
  database.DB.Save(&product)
}

is there some method for gorm to update exactly what is not an empty string, instead of writing such an if construct?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
E
Evgeny Mamonov, 2021-08-16
@kireke

I have not seen this, but, in principle, if desired, you can do it with the help of reflection.
But you will have to pay for reflection with performance :)
If you need an implementation example, let me know, I'll do it.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question