GORM 提供了 Set, Get, InstanceSet, InstanceGet 方法来允许用户传值给 勾子 或其他方法

Gorm 中有一些特性用到了这种机制,如迁移表格时传递表格选项。

  1. // 创建表时添加表后缀
  2. db.Set("gorm:table_options", "ENGINE=InnoDB").AutoMigrate(&User{})

Set / Get

使用 Set / Get 传递设置到钩子方法,例如:

  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

使用 InstanceSet / InstanceGet 传递设置到 *Statement 的钩子方法,例如:

  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. // 在创建关联时,GORM 创建了一个新 `*Statement`,所以它不能读取到其它实例的设置
  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{})