如何使用Gorm和Postgres保存用户的地址关系?
package main
import (
"fmt"
"log"
"github.com/jinzhu/gorm"
_ "github.com/jinzhu/gorm/dialects/postgres"
)
var (
pgUri = "postgres://[email protected]:5432/postgres?sslmode=disable"
)
type User struct {
gorm.Model
Email string
Address Address
}
type Address struct {
gorm.Model
Street string
City string
Country string
}
func main() {
db, err := gorm.Open("postgres", pgUri)
if err != nil {
log.Fatalf("Failed to connect Postgres: %v\n", err)
}
// Checked two tables (user, address) created in database
db.AutoMigrate(&User{}, &Address{})
defer db.Close()
u := User{
Email: "[email protected]",
Address: Address{
Street: "One street",
City: "Two city",
Country: "Three country",
},
}
fmt.Println(u)
if err := db.Create(&u).Error; err != nil {
panic(err)
}
if err := db.Save(&u).Error; err != nil {
panic(err)
}
}
用go run main.go
运行后:
{{0 0001-01-01 00:00:00 +0000 UTC 0001-01-01 00:00:00 +0000 UTC <nil>} [email protected] {{0 0001-01-01 00:00:00 +0000 UTC 0001-01-01 00:00:00 +0000 UTC <nil>} One street Two city Three country}}
它将创建一个新用户,但不创建任何地址。
您缺少Address
关联中的外键。对于具有一个关系,必须存在一个外键字段,会将模型所属的主键保存到此字段中。
type User struct {
gorm.Model
Email string
Address Address // One-To-One relationship (has one - use Address's UserID as foreign key)
}
type Address struct {
gorm.Model
UserID uint
Street string
City string
Country string
}