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

标签 postgresql go go-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}}

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

最佳答案

您在 Address 关联中缺少外键。对于 has one 关系,外键字段必须存在,owned 会将属于它的模型的主键保存到这个字段中。

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
}

关于postgresql - 如何保存与 Gorm 的一对一关系?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59713423/

相关文章:

postgresql - 在 PostgreSQL 中递归聚合父级

sql - 使用 gorm golang 在多个表中进行动态列搜索

go - 返回正确的列数,但所有行均为空

go - 如何使用 GORM (Go) 进行级联操作

node.js - Sequelize 中的内部连接查询引用多个表

c - 将 pg_config 与 waf 一起使用

windows - 系统调用 - 如何在 Go 中使用 LPWSTR?

logging - 在 Go 中记录多个返回值

go - 如何在 golang 的 RESTful api 中维护应用程序状态

postgresql - 用于 postgres 的 liquibase maven 插件生成的 databasechangelog 的插入查询中区分大小写的列名