我有以下2個gorm模型// Day is a corresponding day entrytype Day struct { gorm.Model Dateday string `json:"dateday" gorm:"type:date;NOT NULL"` Nameday string `json:"nameday" gorm:"type:varchar(100);NOT NULL"` Something sql.NullString `json:"something"` Holyday bool `json:"holyday"`}type Week struct { gorm.Model Start Day End Day}但是,在執(zhí)行遷移之后db.AutoMigrate(&Day{})db.AutoMigrate(&Week{})登錄數(shù)據(jù)庫并描述表weekspostgres-# \d+ weeks; Table "public.weeks" Column | Type | Collation | Nullable | Default | Storage | Stats target | Description------------+--------------------------+-----------+----------+-----------------------------------+---------+--------------+------------- id | integer | | not null | nextval('weeks_id_seq'::regclass) | plain | | created_at | timestamp with time zone | | | | plain | | updated_at | timestamp with time zone | | | | plain | | deleted_at | timestamp with time zone | | | | plain | |Indexes: "weeks_pkey" PRIMARY KEY, btree (id) "idx_weeks_deleted_at" btree (deleted_at)我沒有看到start/end字段,大概也應(yīng)該是day表的外鍵(確實存在)這是為什么?
1 回答

慕萊塢森
TA貢獻1810條經(jīng)驗 獲得超4個贊
要設(shè)置一對一的關(guān)系,您還需要將 id 字段添加到 struct。默認情況下,您應(yīng)該將其命名為[YourFieldName]ID,如果您想為 id 字段使用其他名稱,您可以通過標(biāo)簽來完成(有關(guān)更多詳細信息,請參閱文檔),例如:
type Week struct {
gorm.Model
Start Day
End Day `gorm:"foreignkey:EndRefer"`
StartID uint
EndRefer uint
}
但請注意,AutoMigrate不能創(chuàng)建外鍵約束(這里是相關(guān)問題)。你必須自己設(shè)置AddForeignKey方法。
- 1 回答
- 0 關(guān)注
- 203 瀏覽
添加回答
舉報
0/150
提交
取消