Your Question
update 接口是否可以更新主键的值?
Can the update interface update the primary key value?
The document you expected this should be explained
我的model定义如下
type person struct {
Name string `gorm:"primary_key"`
ID int
Sex int
}
当我使用Update操作时我想去更新主键, 该流程下既没有报错也没有修改数据.
p := &person{
Name: "a",
}
if err = db.Model(p).Update("name", "sd").Error; err != nil {
fmt.Println("Error: ", err)
return
}
My model is defined as follows:
type person struct {
Name string `gorm:"primary_key"`
ID int
Sex int
}
When I use the Update operation, I want to update the primary key. In this process, no error is reported and no data is modified.
p := &person{
Name: "a",
}
if err = db.Model(p).Update("name", "sd").Error; err != nil {
fmt.Println("Error: ", err)
return
}
Expected answer
希望能够更新主键值
You want to be able to update the primary key value.
Comment From: li-jin-gou
I use Gorm V2 to run it.
type User struct {
Name string `gorm:"primarykey"`
Age uint
}
func TestGORM(t *testing.T) {
user := User{Name: "jinzhu"}
DB.Create(&user)
DB.Model(&User{}).Where("name = ?", "jinzhu").Updates(map[string]interface{}{
"name": "kinggo",
})
var res User
if err := DB.Where("name = ?", "kinggo").First(&res).Error; err != nil {
t.Errorf("Failed, got error: %v", err)
}
}
result:
[0.864ms] [rows:1] INSERT INTO `users` (`name`,`age`,`birthday`,`company_id`,`manager_id`,`active`) VALUES ("jinzhu",0,NULL,NULL,NULL,false)
[0.870ms] [rows:1] UPDATE `users` SET `name`="kinggo" WHERE name = "jinzhu"
[0.121ms] [rows:1] SELECT * FROM `users` WHERE name = "kinggo" ORDER BY `users`.`name` LIMIT 1
--- PASS: TestGORM (0.00s)
so i think gorm can update the primary key value.
Comment From: TomCream
I use
Gorm V2to run it.
`` type User struct { Name stringgorm:"primarykey"` Age uint } func TestGORM(t *testing.T) { user := User{Name: "jinzhu"}DB.Create(&user)
DB.Model(&User{}).Where("name = ?", "jinzhu").Updates(map[string]interface{}{ "name": "kinggo", }) var res User if err := DB.Where("name = ?", "kinggo").First(&res).Error; err != nil { t.Errorf("Failed, got error: %v", err) } } ```
result:
[0.864ms] [rows:1] INSERT INTO `users` (`name`,`age`,`birthday`,`company_id`,`manager_id`,`active`) VALUES ("jinzhu",0,NULL,NULL,NULL,false) [0.870ms] [rows:1] UPDATE `users` SET `name`="kinggo" WHERE name = "jinzhu" [0.121ms] [rows:1] SELECT * FROM `users` WHERE name = "kinggo" ORDER BY `users`.`name` LIMIT 1 --- PASS: TestGORM (0.00s)so i think gorm can update the primary key value.
should be primary_key not primarykey