猿问

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

如何保存用户与 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}}

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


叮当猫咪
浏览 163回答 1
1回答

RISEBY

您在关联中缺少外键Address。对于一个has one的关系,必须存在一个外键字段,拥有者会将其所属模型的主键保存到这个字段中。type User struct {&nbsp; &nbsp; gorm.Model&nbsp; &nbsp; Email&nbsp; &nbsp;string&nbsp; &nbsp; Address Address // One-To-One relationship (has one - use Address's UserID as foreign key)}type Address struct {&nbsp; &nbsp; gorm.Model&nbsp; &nbsp; UserID&nbsp; uint&nbsp; &nbsp; Street&nbsp; string&nbsp; &nbsp; City&nbsp; &nbsp; string&nbsp; &nbsp; Country string}
随时随地看视频慕课网APP

相关分类

Go
我要回答