Gorm only updates a field

Gorm only updates a field

background

During development, you may encounter that you need to update a field of this piece of data, but you do not want to modify its UpdatedAtfield.
Such as: data views.

Normal update

...
err = d.db.Model(&repository.UserInfo{
    
    }).Where("id = ?", id).Update(repository.UserInfo{
    
    
			ViewsCount: viewsCount+1,
		}).Error
...

Only update a field ( UpdatedAt字段not update)

...
err = d.db.Model(&repository.UserInfo{
    
    }).Where("id = ?", id).UpdateColumn(map[string]interface{
    
    }{
    
    
			"views_count": viewsCount++,
			}).Error
...

Update a field to the default value (same as above)

Such as: the database is set to int type, when updating, set 1 to 0. At this time, in Gorm, this field is not updated, it thinks it is 结构体初始化时的默认值.
If you need to update a field to the default value, you can use the operation under the tree.

...
err = d.db.Model(&repository.UserInfo{
    
    }).Where("id = ?", id).UpdateColumn(map[string]interface{
    
    }{
    
    
			"is_hidden": false,
			}).Error
...

Guess you like

Origin blog.csdn.net/LitongZero/article/details/109724305