InfoSphere/GORM 中文版/ 返回书籍
Advanced Topics

Constraints

qianmoQqianmoQ· 更新于 2026-09-15· 阅读 4 分钟· 0 次阅读

登录后可跨设备保存划线和私人笔记登录

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

type UserIndex struct {
  Name  string `gorm:"check:name_checker,name <> 'jinzhu'"`
  Name2 string `gorm:"check:name <> 'jinzhu'"`
  Name3 string `gorm:"check:,name <> 'jinzhu'"`
}

Index Constraint

Checkout Database Indexes

Foreign Key Constraint

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

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

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

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
}

GitHub tag (latest SemVer)

评论

登录后参与评论

正在加载评论…