GORM allows create database constraints with tag, constraints will be created when AutoMigrate or CreateTable with GORM

CHECK Constraint

Create CHECK constraints with tag check

1. type UserIndex struct {
2. Name  string `gorm:"check:name_checker,name <> 'jinzhu'"`
3. Name2 string `gorm:"check:name <> 'jinzhu'"`
4. Name3 string `gorm:"check:,name <> 'jinzhu'"`
5. }

Index Constraint

Checkout Database Indexes

Foreign Key Constraint

GORM will creates foreign keys constraints for associations, you can disable this feature during initialization:

1. db, err := gorm.Open(sqlite.Open("gorm.db"), &gorm.Config{
2. DisableForeignKeyConstraintWhenMigrating: true,
3. })

GORM allows you setup FOREIGN KEY constraints’s OnDelete, OnUpdate option with tag constraint, for example:

1. type User struct {
2. gorm.Model
3. CompanyID  int
4. Company    Company    `gorm:"constraint:OnUpdate:CASCADE,OnDelete:SET NULL;"`
5. CreditCard CreditCard `gorm:"constraint:OnUpdate:CASCADE,OnDelete:SET NULL;"`
6. }

8. type CreditCard struct {
9. gorm.Model
10. Number string
11. UserID uint
12. }

14. type Company struct {
15. ID   int
16. Name string
17. }