【问题标题】:How to update the nested tables in sql using gorm?如何使用gorm更新sql中的嵌套表?
【发布时间】:2019-02-06 02:55:31
【问题描述】:

这里的代码是用 Go 编写的。我正在使用两个表,其中一个表的外键引用另一个表的主键。假设我有一个定义如下结构的数据库:

   type User struct{
       ID uint `gorm:"primary_key;column:id"`
       Name string `gorm:"column:name"`
       Place place
       PlaceID
   }

   type Place struct{
       ID uint `gorm:"primary_key;column:id"`
       Name string `gorm:"column:name"`
       Pincode uint `gorm:"column:pincode"`
   }

而 sql 架构是:

create table place(
    id int(20) NOT NULL AUTO_INCREMENT,
    name varchar(100) NOT NULL,
    pincode uint(20) NOT NULL,
    PRIMARY KEY (id),
)

create table user(
    id int(20) NOT NULL AUTO_INCREMENT,
    name varchar(100) NOT NULL,
    place_id uint(20) NOT NULL,
    PRIMARY KEY (id),
    FOREIGN KEY (place_id) REFERENCES place(id)
)

现在通过 gorm 将用户插入为:

  place := Place{Name:"new delhi",Pincode:1234}
  user := User{Name: "sam", Age: 15, Place: place}
  err = db.Debug().Create(&user).Error

  //It  inserts to both user and place table in mysql
  //now while updating to name in user table as Samuel and place as 
  //following

  place := Place{Name:"mumbai",Pincode:1234}
  err = db.Debug().Model(&User{}).Where("id =?", 
   1,).Update(&user{Name:"Samuel",Place:place}).Error

它更新用户表中的行,但在地方表中创建一个新行。但它应该更新地方表中的匹配行而不是创建一个新行

有什么办法吗?这里我没有使用自动迁移功能来创建数据库表。

【问题讨论】:

    标签: sql go foreign-keys one-to-one go-gorm


    【解决方案1】:

    您的问题的答案应在关系或Association Mode 中寻求。 下面的示例展示了如何为 many to manyhas many 添加新的关联,替换当前的关联 有一个属于

    db.Model(&user).Association("Place").Append(Place{Name:"mumbai",Pincode:1234})
    

    或者您可以用新的关联替换当前关联:

    db.Model(&user).Association("Place").Replace(Place{Name:"mumbai",Pincode:1234},Place{Name:"new delhi",Pincode:1234})

    【讨论】:

      【解决方案2】:

      可能它正在创建一个新行,因为您没有在Place{Name:"mumbai",Pincode:1234} 上设置 ID。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2019-07-10
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多