Your Question
I want to skip '' values when updating with Upsert.
The document you expected this should be explained
type Test struct {
Id int64 `gorm:"column:id; primaryKey"`
Name string `gorm:"column:name"`
Age int `gorm:"column:age"`
}
d.MDb.Debug().Table("test").Clauses(clause.OnConflict{
Columns: []clause.Column{{Name: "id"}},
DoUpdates: clause.AssignmentColumns([]string{"name", "age"}),
}).CreateInBatches(&test, 10)
Expected answer
We have a record
|id|nam|age|
|--|---|---|
|1|hello|18|
I want to update this record, but I want to keep the value of 'hello'
{"id": 1, "name":"", "age": 19}
Comment From: dkasyanov
Hi,
I believe that you need a custom function in the Clause. So you could check input values.
For example to omit name field if it is an empty string you can use next code:
var test Test
d.MDb.Debug().Table("test").Clauses(clause.OnConflict{
Columns: []clause.Column{{Name: "id"}},
DoUpdates: func(c *gorm.DB) *gorm.DB {
updates := map[string]interface{}{"age": test.Age}
if test.Name != "" {
updates["name"] = test.Name
}
return c.Model(&Test{}).Updates(updates)
},
}).CreateInBatches(&test, 10)
This code defines a map of updates that includes the age column, and optionally includes the name column if it is not an empty string. The Updates method is then used to apply the updates to the test table.
Comment From: luizcarlosrodrigues
What is the best way when you don´t know wich fields are been updated and you need to preserve the values on the association that already has values.
database.Db.WithContext(ctx).Session(&gorm.Session{FullSaveAssociations: true}).Clauses(clause.Returning{}).Updates(&client)