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.

  1. // Add table suffix when creating tables
  2. db.Set("gorm:table_options", "ENGINE=InnoDB").AutoMigrate(&User{})

Set / Get

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

  1. type User struct {
  2. gorm.Model
  3. CreditCard CreditCard
  4. // ...
  5. }
  6. func (u *User) BeforeCreate(tx *gorm.DB) error {
  7. myValue, ok := tx.Get("my_value")
  8. // ok => true
  9. // myValue => 123
  10. }
  11. type CreditCard struct {
  12. gorm.Model
  13. // ...
  14. }
  15. func (card *CreditCard) BeforeCreate(tx *gorm.DB) error {
  16. myValue, ok := tx.Get("my_value")
  17. // ok => true
  18. // myValue => 123
  19. }
  20. myValue := 123
  21. db.Set("my_value", myValue).Create(&User{})

InstanceSet / InstanceGet

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

  1. type User struct {
  2. gorm.Model
  3. CreditCard CreditCard
  4. // ...
  5. }
  6. func (u *User) BeforeCreate(tx *gorm.DB) error {
  7. myValue, ok := tx.InstanceGet("my_value")
  8. // ok => true
  9. // myValue => 123
  10. }
  11. type CreditCard struct {
  12. gorm.Model
  13. // ...
  14. }
  15. // When creating associations, GORM creates a new `*Statement`, so can't read other instance's settings
  16. func (card *CreditCard) BeforeCreate(tx *gorm.DB) error {
  17. myValue, ok := tx.InstanceGet("my_value")
  18. // ok => false
  19. // myValue => nil
  20. }
  21. myValue := 123
  22. db.InstanceSet("my_value", myValue).Create(&User{})