Answer the question
In order to leave comments, you need to log in
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)
}
Answer the question
In order to leave comments, you need to log in
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 questionAsk a Question
731 491 924 answers to any question