package main
import (
"time"
"gorm.io/driver/sqlite"
"gorm.io/gorm"
"gorm.io/gorm/logger"
)
type Country struct {
ID int
Name string `gorm:"uniqueIndex"`
CreatedAt time.Time
UpdatedAt time.Time
}
type Operator struct {
ID int
CountryID int
Country Country
Name string
Code string
CreatedAt time.Time
UpdatedAt time.Time
}
func main() {
config := gorm.Config{
Logger: logger.Default.LogMode(logger.Info),
}
db, err := gorm.Open(sqlite.Open("test.db"), &config)
if err != nil {
panic(err)
}
db.AutoMigrate(&Country{}, &Operator{})
test1 := Operator{Country: Country{Name: "Test"}, Name: "Test1", Code: "A"}
db.Create(&test1)
test2 := Operator{Country: Country{Name: "Test"}, Name: "Test2", Code: "B"}
db.Create(&test2)
}
通过上面的代码,test1创建了一个新的国家和操作员,并且在xqlite数据库中的operator_id是正确的。
对于test2, operator_id设置为0。如何创建test2条目并使其引用现有的国家?
由于uniqueIndex
对Country
的约束,您对db.Create(&test2)
的调用可能失败。一定要检查你的错误!
您可能会发现工作是首先将单个Country
条目插入到DB中,如下所示:
testCountry := Country{Name: "Test"}
if result := db.Create(&testCountry); result.Error != nil {
// do something with result.Error
}
根据我最近使用Gorm的经验,假设db.Create
成功,它将填充testCountry.ID
(总是检查你的错误!)之后,创建test1
和test2
,如下所示:
test1 := Operator{
Country: testCountry,
CountryID: testCountry.ID,
Name: "Test1",
Code: "A",
}
if result := db.Create(&test1); result.Error != nil {
// do something with result.Error
}
[... do the same thing with test2 ...]