gorm 没有在数据库模式中建立外键关系
gorm not establishing foreign key relationshop in the database schema
我有以下 2 gorm
个型号
// Day is a corresponding day entry
type 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{})
登录数据库并描述 table weeks
postgres-# \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
table 的外键(确实存在)
这是为什么?
要设置一对一关系,您还需要将 id 字段添加到结构中。默认情况下,你应该将其命名为 [YourFieldName]ID
,如果你想为 id 字段使用其他名称,你可以通过标签来实现(参见 docs for more details),例如:
type Week struct {
gorm.Model
Start Day
End Day `gorm:"foreignkey:EndRefer"`
StartID uint
EndRefer uint
}
但请注意,AutoMigrate
无法创建外键约束(here's related issue). You have to set it yourself with AddForeignKey
method。
我有以下 2 gorm
个型号
// Day is a corresponding day entry
type 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{})
登录数据库并描述 table weeks
postgres-# \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
table 的外键(确实存在)
这是为什么?
要设置一对一关系,您还需要将 id 字段添加到结构中。默认情况下,你应该将其命名为 [YourFieldName]ID
,如果你想为 id 字段使用其他名称,你可以通过标签来实现(参见 docs for more details),例如:
type Week struct {
gorm.Model
Start Day
End Day `gorm:"foreignkey:EndRefer"`
StartID uint
EndRefer uint
}
但请注意,AutoMigrate
无法创建外键约束(here's related issue). You have to set it yourself with AddForeignKey
method。