【问题标题】:How to save one to one relations with Gorm?如何保存与Gorm的一对一关系?
【发布时间】:2020-01-13 09:07:46
【问题描述】:

如何保存用户与 Gorm 和 Postgres 的地址关系?

package main

import (
    "fmt"
    "log"

    "github.com/jinzhu/gorm"
    _ "github.com/jinzhu/gorm/dialects/postgres"
)

var (
    pgUri = "postgres://postgres@127.0.0.1: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: "some@one.com",
        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>} some@one.com {{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 go-gorm


    【解决方案1】:

    您在 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
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-07-12
      • 1970-01-01
      • 2011-12-02
      • 2020-05-16
      • 1970-01-01
      相关资源
      最近更新 更多