GORM 允许通过标签创建数据库约束,约束会在通过 GORM 进行 AutoMigrate 或创建数据表时被创建。
通过 check 标签创建检查约束
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 选项设置外键约束,例如:
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 }
Copyright© 2013-2020
All Rights Reserved 京ICP备2023019179号-8