【问题标题】:How to work with has many relation in gorm?如何与gorm有很多关系?
【发布时间】:2021-04-15 09:07:12
【问题描述】:
import (
    "gorm.io/gorm"
    "gorm.io/driver/postgres"
)

type School struct {
    gorm.Model
    Students        []Student      `json:"students"`
}

type Student struct {
    gorm.Model
    Name            string         `json:"name"`
}

func init() {
    //connect to db first
    conn, err := gorm.Open(postgres.New(postgres.Config{
        DSN:                  dbUri,
        PreferSimpleProtocol: true,
    }), &gorm.Config{})
    if err != nil {
        log.Fatal(err)
    }

    db = conn
    db.AutoMigrate(&Student{}, &School{})
}

创建结构并自动迁移它会给我一个错误。你知道这是为什么吗?另外,你如何使用在 gorm 中有很多关系,它在 postgres 中创建了什么样的数据?

错误 - 需要为关系定义一个有效的外键或者需要实现 Valuer/Scanner 接口

【问题讨论】:

    标签: postgresql go go-gorm


    【解决方案1】:

    您需要将SchoolID 字段添加到您的Student。请参阅docs here 了解完整用法。

    type Student struct {
        gorm.Model
        SchoolID        uint
        Name            string         `json:"name"`
    }
    

    要回答第二部分,它将为您创建两个表。学校和学生。学生将有一个指向学校 ID 的外键。我会read the docs 了解更多这是如何工作的。

    【讨论】:

    • 谢谢@Christian!我认为它会在学校表本身中创建一个学生 ID 数组。
    猜你喜欢
    • 2021-10-27
    • 1970-01-01
    • 2021-12-26
    • 1970-01-01
    • 1970-01-01
    • 2021-12-28
    • 1970-01-01
    • 2018-08-20
    • 1970-01-01
    相关资源
    最近更新 更多