【问题标题】:why create a new row when gorm update associations为什么在gorm更新关联时创建一个新行
【发布时间】:2021-10-16 10:22:45
【问题描述】:

我遵循文档代码相同的结构并迁移

这是我的模型

type User struct {
    gorm.Model
    AddressID uint           ``
    Address   UserAddress    `gorm:"references:ID;constraint:OnUpdate:CASCADE,OnDelete:SET NULL"`
}
type UserAddress struct {
    gorm.Model
    Address   string         `gorm:"type:varchar(50);notNull"`
}

迁移和创建数据时文档工作正常

    db.AutoMigrate(&UserAddress{})

    db.AutoMigrate(&User{})

但是当我尝试更新数据时使用关联

    user := &User{
        ID:        1,
        AddressID: 1,
        Address: UserAddress{
            Address: "new address",
        },
    }

    db.Session(&gorm.Session{FullSaveAssociations: true}).Updates(&user)

文件说:

如果你想更新关联的数据,你应该使用 FullSaveAssociations 模式:

那么它仍然会创建一个新的地址数据并更新user.address_id

INSERT INTO `user_address` (`address`,`created_at`,`updated_at`,`deleted_at`) VALUES ('changed','2021-08-13 14:07:39.149','2021-08-13 14:07:39.149',NULL) ON DUPLICATE KEY UPDATE `address`=VALUES(`address`),`created_at`=VALUES(`created_at`),`updated_at`=VALUES(`updated_at`),`deleted_at`=VALUES(`deleted_at`)

我在这里错过了什么或者它根本不起作用?

【问题讨论】:

    标签: go go-gorm


    【解决方案1】:

    您没有为地址提供唯一的 ID。因此它使用自动增量 ID 创建新的地址记录。并更新与之关联的 ID 值。

    user := &User{
            ID:        1,
            AddressID: 1,
            Address: UserAddress{
                ID: 1,
                Address: "new address",
            },
        }
    
    

    【讨论】:

    • 我想。在地址中设置它。此 AddressID 的目的是指定 User 和 Address 之间的关系。不创建 ID 为 1 的 UserAddress。
    • 我已经验证过了。在您当前的模型定义中,您需要指定 UserAddress.ID。然后不会创建新行。
    • 我尝试添加 UserAddress.ID 并更新(必须使用 Session(&gorm.Session{FullSaveAssociations: true})),它可以工作。差点误会gorm :3,非常感谢,
    猜你喜欢
    • 1970-01-01
    • 2018-01-29
    • 1970-01-01
    • 2021-07-07
    • 2021-10-12
    • 2010-10-21
    • 2022-11-30
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多