优惠全部云服务器首月 8 折,优惠码 CLOUD去领取

AutoMigrate 不生成自引用外键

· 阅读约 2 分钟

问题内容

我正在尝试让自引用键在我的模型中工作。由于某种原因,外键关系没有被创建。我尝试了多种结构标记的变体,但没有成功。

我有自己的 mixin:

type mixin struct {
    id        uint      `json:"id"`
    createdat time.time `json:"created_at"`
    updatedat time.time `json:"updated_at"`
    deleted   bool      `json:"deleted"`
}

此模型中出现了问题,当我在 postgres 上运行 automigrate 时,不会创建 parenttaskid 外键约束。

type Task struct {
    Mixin
    Content  string    `gorm:"not null; default:Empty Task" json:"content"`
    Deadline time.Time `json:"deadline,omitempty"`
    Priority uint      `json:"priority,omitempty"`
    Complete bool      `json:"complete,omitempty"`

    // Relations
    BucketID *uint   `gorm:"not null" json:"bucket_id"`
    Bucket   *Bucket `gorm:"foreignKey: BucketID" json:"-"`

    ParentTaskID *uint `gorm:"not null" json:"parent_task_id"`
    ParentTask   *Task `gorm:"foreignKey: ParentTaskID" json:"-"`
}

正确答案

我可以确认这似乎是 gorm 中的一个错误。我创建了 和 来重现该错误。

您可以在 github 中订阅更新。

本篇关于《AutoMigrate 不生成自引用外键》的介绍就到此结束啦,但是学无止境,想要了解学习更多关于Golang的相关知识,请关注公众号!

相关文章

更多「网站和优化」文章服务器使用指南