InfoSphere/GORM 中文版/ 返回书籍
Tutorials

Settings

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

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

GORM provides Set, Get, InstanceSet, InstanceGet methods allow users pass values to hooks or other methods

GORM uses this for some features, like pass creating table options when migrating table.


db.Set("gorm:table_options", "ENGINE=InnoDB").AutoMigrate(&User{})

Set / Get

Use Set / Get pass settings to hooks methods, for example:

type User struct {
  gorm.Model
  CreditCard CreditCard
  
}

func (u *User) BeforeCreate(tx *gorm.DB) error {
  myValue, ok := tx.Get("my_value")
  
  
}

type CreditCard struct {
  gorm.Model
  
}

func (card *CreditCard) BeforeCreate(tx *gorm.DB) error {
  myValue, ok := tx.Get("my_value")
  
  
}

myValue := 123
db.Set("my_value", myValue).Create(&User{})

InstanceSet / InstanceGet

Use InstanceSet / InstanceGet pass settings to current *Statement‘s hooks methods, for example:

type User struct {
  gorm.Model
  CreditCard CreditCard
  
}

func (u *User) BeforeCreate(tx *gorm.DB) error {
  myValue, ok := tx.InstanceGet("my_value")
  
  
}

type CreditCard struct {
  gorm.Model
  
}


func (card *CreditCard) BeforeCreate(tx *gorm.DB) error {
  myValue, ok := tx.InstanceGet("my_value")
  
  
}

myValue := 123
db.InstanceSet("my_value", myValue).Create(&User{})

GitHub tag (latest SemVer)

评论

登录后参与评论

正在加载评论…