我有以下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}但是,執行遷移后db.AutoMigrate(&Day{})db.AutoMigrate(&Week{})登錄數據庫并描述表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字段,它大概也應該是表的外鍵day(確實存在)這是為什么?
1 回答

米琪卡哇伊
TA貢獻1998條經驗 獲得超6個贊
要設置一對一關系,您還需要將 id 字段添加到結構中。默認情況下,您應該將其命名為[YourFieldName]ID
,如果您想為 id 字段使用其他名稱,您可以通過標簽來完成,例如:
type Week struct {
? ? gorm.Model
? ? Start? ? Day
? ? End? ? ? Day `gorm:"foreignkey:EndRefer"`
? ? StartID? uint
? ? EndRefer uint
}
但要注意,AutoMigrate
不能創建外鍵約束。
- 1 回答
- 0 關注
- 162 瀏覽
添加回答
舉報
0/150
提交
取消