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. }
  7. type CreditCard struct {
  8. gorm.Model
  9. Number string
  10. UserID uint
  11. }
  12. type Company struct {
  13. ID int
  14. Name string
  15. }