我有以下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 关注
- 124 浏览
添加回答
举报
0/150
提交
取消