问题描述
我正在尝试让自引用键在我的模型中工作。出于某种原因,外键关系没有被创建。我尝试了很多结构标签的变体,但都无济于事。
我有自己的 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 中的一个错误。我创建了重现错误的 an issue 和 a test case。
您可以在 github 中订阅更新。