约束

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 标签的 OnDeleteOnUpdate 选项设置外键约束,例如:

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
}

Platinum Sponsors

Become a Sponsor!

Platinum Sponsors

Become a Sponsor!

OpenCollective Sponsors