Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[Question] #636

Open
al-ship opened this issue Feb 6, 2023 · 1 comment
Open

[Question] #636

al-ship opened this issue Feb 6, 2023 · 1 comment
Assignees

Comments

@al-ship
Copy link

al-ship commented Feb 6, 2023

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.

@mimani68
Copy link

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}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

3 participants