【发布时间】: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