[Question]
al-ship opened this issue · comments
Document Link
[
](https://gorm.io/docs/update.html)Your Question
db.Model(&user).Updates(map[string]interface{}{"name": "hello", "age": 18, "active": false})
// UPDATE users SET name='hello', age=18, active=false, updated_at='2013-11-17 21:34:10' WHERE id=111;
it updates all fields and dependent objects in user!
Expected answer
I expect to update only fields specified in map.
Could specify your exact problem! While i simulate your scenario, no weird stuff has happened.
package main
import (
"fmt"
"gorm.io/driver/mysql"
"gorm.io/gorm"
)
type User struct {
ID uint `gorm:"primarykey"`
Name string `gorm:"not null"`
Family string `gorm:"not null"`
Age int `gorm:"not null"`
}
func main() {
dsn := "root:123@tcp(127.0.0.1:3306)/app?charset=utf8mb4&parseTime=True&loc=Local"
db, err := gorm.Open(mysql.Open(dsn), &gorm.Config{})
if err != nil {
panic(err)
}
// Migrate the schema
db.AutoMigrate(&User{})
// Create a user
user := User{Name: "John", Family: "Doe", Age: 30}
db.Create(&user)
// Update some attribute of record
db.Model(&user).Updates(&User{Name: "Mahdi"})
// Print the updated user
var updatedUser User
db.Where("name = ?", "Mahdi").First(&updatedUser)
fmt.Println(updatedUser)
}
Developers can see the below result while trying to run the application in the meantime.
go run app.go
And the output was
{8 Mahdi Doe 30}