当前位置: > > > > 如何挽救与Gorm的一对一关系?
如何挽救与Gorm的一对一关系?
来源:stackoverflow
2024-04-25 22:06:41
0浏览
收藏
哈喽!今天心血来潮给大家带来了《如何挽救与Gorm的一对一关系?》,想必大家应该对Golang都不陌生吧,那么阅读本文就都不会很困难,以下内容主要涉及到,若是你正在学习Golang,千万别错过这篇文章~希望能帮助到你!
问题内容
如何保存用户与 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 运行 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 关联中的外键。对于 has one 关系,必须存在外键字段,所拥有的 会将属于它的模型的主键保存到该字段中。
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
}
以上就是《如何挽救与Gorm的一对一关系?》的详细内容,更多关于的资料请关注米云公众号!
