SoFunction
Updated on 2025-03-05

Gorm updates zero-value problem solution ideas and processes

1. Preface

To facilitate the description of tutorial examples, here are the mysql table structure definition and the golang structure definition.

The following is the tutorialfoodsTable structure definition:

CREATE TABLE `foods` (
  `id` int(11) NOT NULL AUTO_INCREMENT COMMENT 'Product ID',
  `title` varchar(100) NOT NULL COMMENT 'Trade Name',
  `price` float DEFAULT '0' COMMENT 'Commodity Price',
  `stock` int(11) DEFAULT '0' COMMENT 'Commodity Inventory',
  `type` int(11) DEFAULT '0' COMMENT 'Product Type',
  `create_time` datetime NOT NULL COMMENT 'Product creation time',
  PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

Below is the golang structure type corresponding to the foods table

//commoditytype Food struct {
	Id         int
	Title      string
	Price      float32
	Stock      int
	Type       int
	//mysql datetime, date type field, can be bound to golang type. For detailed instructions, please refer to the chapter on the Gorm connection database.	CreateTime 
}
//Bind table name for Foodfunc (v Food) TableName() string {
	return "foods"
}

2. Common methods for update records of gorm

1. Save

Used to save the value of the model variable.

Tip: It is equivalent to updating all model field values ​​based on the primary key id.

food := Food{}
//First query a record and save it in the model variable food//Equivalent to: SELECT * FROM `foods` WHERE (id = '2') LIMIT 1("id = ?", 2).Take(&food)
//Modify the value of the food model = 100
//Equivalent to: UPDATE `foods` SET `title` = 'Cola', `type` = '0', `price` = '100', `stock` = '26', `create_time` = '2018-11-06 11:12:04' WHERE `foods`.`id` = '2'(&food)

2. Update

Update single field values

//Example 1://Update the table record corresponding to the food model//Equivalent to: UPDATE `foods` SET `price` = '25' WHERE `foods`.`id` = '2'(&food).Update("price", 25)
//Update the price field value by using the value of the primary key id of the food model as the where condition.//Example 2://The above example is just to update a record. What if we want to make all records more?//Equivalent to: UPDATE `foods` SET `price` = '25'(Food{}).Update("price", 25)
//Note that the Model parameter here uses Food{}, a new blank model variable is generated without any records bound.//Because the id of Food{} is empty, the gorm library will not use id as a condition, and the where statement is empty//Example 3://Update records based on custom conditions, not based on primary key id//Equivalent to: UPDATE `foods` SET `price` = '25' WHERE (create_time > '2018-11-06 20:00:00')(Food{}).Where("create_time > ?", "2018-11-06 20:00:00").Update("price", 25)

3. Updates

Update multiple field values

//Example 1://Update fields through structure variable settingsupdataFood := Food{
		Price:120,
		Title:"Lemon Sprite",
	}
//Update database records according to food model//Equivalent to: UPDATE `foods` SET `price` = '120', `title` = 'lemon Sprite' WHERE `foods`.`id` = '2'//Updates will ignore the zero value field of the updateFood structure variable, so the generated SQL statements only have price and title fields.(&food).Updates(&updataFood)
//Example 2://Update records based on custom conditions, not based on model idupdataFood := Food{
		Stock:120,
		Title:"Lemon Sprite",
	}
//Set Where conditions, Model parameters bind an empty model variable//Equivalent to: UPDATE `foods` SET `stock` = '120', `title` = 'lemon Sprite' WHERE (price > '10')(Food{}).Where("price > ?", 10).Updates(&updataFood)
//Example 3://What should I do if I want to update all field values, including zero values, but I don’t want to ignore empty fields?//Use map type to replace the above structure variable//Define map type, key is string, value is interface{} type, convenient to save any valuedata := make(map[string]interface{})
data["stock"] = 0 //Zero Value Fielddata["price"] = 35
//Equivalent to: UPDATE `foods` SET `price` = '35', `stock` = '0' WHERE (id = '2')(Food{}).Where("id = ?", 2).Updates(data)

Tip: When updating field values ​​through structure variables, the gorm library ignores the zero-value field. That is, the field values ​​equal to 0, nil, "", ", false will be ignored and will not be updated. If you want to update the zero value, you can use the map type instead of the structure.

4. Update expressions

UPDATE foods SET stock = stock + 1 WHERE id = '2'

How to write such an update statement with a calculation expression?

gorm provides Expr function for setting expressions

//Equivalent to: UPDATE `foods` SET `stock` = stock + 1 WHERE `foods`.`id` = '2'(&food).Update("stock", ("stock + 1"))

3. Use struct to update only applies to non-zero values

user:=User{
	Name:"",
	Age:0,
	Actived:false,
}
(&user).Updates(user)
//These zero values ​​will not be updated at this time. If you need to update the zero values, use mapuserMap:=map[string]interface{}{
  "name":"",
  "age":0,
  "actived":0,
}
(&user).Updates(userMap)

This is the article about the solution to the Gorm update zero value problem. For more related content on Gorm update zero value, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!