Search code examples
go-gorm

What's the difference between Gorm Save and Update?


What are the differences between these two ways of updating? Aside from the fact that the 1st way requires a query first. The docs say that updating the second way will ignore zero value fields. Is that also true of the 1st?

user = User{1, "old name"}
user2 = User{2, "old name"}

//fist way
db.First(&user)
user.Name = "new name"
db.Save(&user)

//second way
user2.Name = "new name"
db.Model(&user2).Updates(&user2)

Solution

  • As per Gorm API documentation (https://pkg.go.dev/gorm.io/gorm#DB.Save), Save function will create a Primary Key for an entity if it does not exist as well as update fields, while Update will just update fields.