如何与Gorm保持一对一的关系?

问题描述 投票:0回答:1

如何使用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}}

它将创建一个新用户,但不创建任何地址

postgresql go gorm
1个回答
0
投票

您缺少Address关联中的外键。对于具有一个关系,必须存在一个外键字段,会将模型所属的主键保存到此字段中。

Doc

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
}
© www.soinside.com 2019 - 2024. All rights reserved.