扫码一下
查看教程更方便
gorm 允许通过标签创建数据库约束,约束会在通过 gorm 进行 automigrate 或创建数据表时被创建。
通过 check
标签创建检查约束
type userindex struct {
name string `gorm:"check:name_checker,name <> 'jinzhu'"`
name2 string `gorm:"check:name <> 'jinzhu'"`
name3 string `gorm:"check:,name <> 'jinzhu'"`
}
查看 数据库索引 获取详情
gorm 会为关联创建外键约束,我们可以在初始化过程中禁用此功能:
db, err := gorm.open(sqlite.open("gorm.db"), &gorm.config{
disableforeignkeyconstraintwhenmigrating: true,
})
gorm 允许我们通过 constraint
标签的 ondelete 、onupdate 选项设置外键约束,例如:
type user struct {
gorm.model
companyid int
company company `gorm:"constraint:onupdate:cascade,ondelete:set null;"`
creditcard creditcard `gorm:"constraint:onupdate:cascade,ondelete:set null;"`
}
type creditcard struct {
gorm.model
number string
userid uint
}
type company struct {
id int
name string
}