【问题标题】:Cannot update entity column with the same value无法更新具有相同值的实体列
【发布时间】:2021-02-20 12:13:50
【问题描述】:

这是一个非常小的程序。它是这样的:

type User struct {
    Id    int64  `gorm:"PRIMARY_KEY;AUTO_INCREMENT"` 
    Name  string `gorm:"size:32;not null"`           
    Email string `gorm:"size:128;not null"`          
}

func main() {
    
    db, err := gorm.Open("mysql", "root@tcp(localhost:3306)/test_db?charset=utf8mb4&parseTime=True&loc=Local")
    if err != nil {
        panic("failed to connect database")
    }
    
    db.Create(&User{
        Name:  "Max",
        Email: "maxluan@gmail.com",
    })

    var user User
    db.Where("name = ?", "Max").First(&user)
    fmt.Println("Max's email:" + user.Email)

    // Update and save
    user.Email = "maxluan2@gmail.com"
    db.Save(user)

    defer db.Close()
}

当我第一次运行程序时。它工作得很好。它创建记录,并更新其电子邮件列。然后我删除了 create 部分并再次运行该程序。我希望它能够获取用户,为电子邮件列分配相同的值并保存。什么都不应该改变。但是程序出现了恐慌。

panic: reflect.Value.Addr of unaddressable value [recovered]
        panic: reflect.Value.Addr of unaddressable value

goroutine 1 [running]:
github.com/jinzhu/gorm.(*Scope).callCallbacks.func1(0xc000234300)
        /home/shiyanlou/gopath/pkg/mod/github.com/jinzhu/gorm@v1.9.16/scope.go:865 +0xb0
panic(0x6f6860, 0x7a5720)
        /usr/local/go/src/runtime/panic.go:969 +0x175
reflect.Value.Addr(0x727200, 0xc000226570, 0x99, 0x3, 0x0, 0x0)
        /usr/local/go/src/reflect/value.go:270 +0x85
github.com/jinzhu/gorm.queryCallback(0xc000234300)
        /home/shiyanlou/gopath/pkg/mod/github.com/jinzhu/gorm@v1.9.16/callback_query.go:84 +0x47b
github.com/jinzhu/gorm.(*Scope).callCallbacks(0xc000234300, 0xc0001de420, 0x3, 0x4, 0x0)
        /home/shiyanlou/gopath/pkg/mod/github.com/jinzhu/gorm@v1.9.16/scope.go:869 +0x83
github.com/jinzhu/gorm.(*DB).First(0xc000229520, 0x727200, 0xc000226570, 0x0, 0x0, 0x0, 0x7b24a0)
        /home/shiyanlou/gopath/pkg/mod/github.com/jinzhu/gorm@v1.9.16/main.go:334 +0x125
github.com/jinzhu/gorm.(*DB).FirstOrCreate(0xc000229520, 0x727200, 0xc000226570, 0x0, 0x0, 0x0, 0xc00011df40)
        /home/shiyanlou/gopath/pkg/mod/github.com/jinzhu/gorm@v1.9.16/main.go:428 +0xa5
github.com/jinzhu/gorm.(*DB).Save(0xc0001f21a0, 0x727200, 0xc000226570, 0xc000226570)
        /home/shiyanlou/gopath/pkg/mod/github.com/jinzhu/gorm@v1.9.16/main.go:473 +0x1bb
main.main()
        /home/project/main.go:28 +0x287
exit status 2

请帮助解释为什么会发生这种情况。谢谢。

【问题讨论】:

  • 你能试试db.Save(&user)吗?

标签: go go-gorm


【解决方案1】:

感谢Riwen

根据gorm doc,在调用save时,应该传入引用。

db.Save(&user) 可以工作。

这是一个低级错误。为避免此类错误,应始终更仔细地阅读文档,特别注意价值与参考。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-12-29
    • 2018-01-28
    • 2019-12-07
    • 1970-01-01
    • 2016-01-14
    • 2021-12-06
    相关资源
    最近更新 更多