Use when defining database rules to enforce data integrity, such as CHECK constraints for value validation or foreign key constraints to manage relationships between tables with ON UPDATE/ON DELETE actions.
GORM allows creating database constraints with tags. Constraints are created during AutoMigrate or CreateTable.
Create CHECK constraints with the check tag. You can specify a constraint name or let GORM generate one:
type UserIndex struct {
Name string `gorm:"check:name_checker,name <> 'jinzhu'"` // Named constraint
Name2 string `gorm:"check:name <> 'jinzhu'"` // Unnamed constraint
Name3 string `gorm:"check:,name <> 'jinzhu'"` // Unnamed (explicit empty name)
}
Syntax: check:constraint_name,expression or check:expression
For index constraints, see the skill.
GORM creates foreign key constraints for associations automatically. You can configure OnDelete and OnUpdate actions with the constraint tag:
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
}
| Action | Description |
|---|---|
CASCADE | Update/delete child rows when parent changes |
SET NULL | Set foreign key to NULL when parent is deleted |
SET DEFAULT | Set foreign key to default value |
RESTRICT | Prevent parent modification if children exist |
NO ACTION | Similar to RESTRICT (database-dependent) |
To disable foreign key constraint creation during migration:
db, err := gorm.Open(sqlite.Open("gorm.db"), &gorm.Config{
DisableForeignKeyConstraintWhenMigrating: true,
})
Use cases:
| Tag | Example | Description |
|---|---|---|
check | gorm:"check:age > 18" | Unnamed CHECK constraint |
check:name,expr | gorm:"check:age_check,age > 18" | Named CHECK constraint |
constraint:OnUpdate | gorm:"constraint:OnUpdate:CASCADE" | Foreign key update action |
constraint:OnDelete | gorm:"constraint:OnDelete:SET NULL" | Foreign key delete action |
| Combined | gorm:"constraint:OnUpdate:CASCADE,OnDelete:SET NULL;" | Both actions |
Spring Boot中的JPA/Hibernate模式,用于实体设计、关系处理、查询优化、事务管理、审计、索引、分页和连接池。