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. }

7. func (u *User) BeforeCreate(tx *gorm.DB) error {
8. myValue, ok := tx.Get("my_value")
9. // ok => true
10. // myValue => 123
11. }

13. type CreditCard struct {
14. gorm.Model
15. // ...
16. }

18. func (card *CreditCard) BeforeCreate(tx *gorm.DB) error {
19. myValue, ok := tx.Get("my_value")
20. // ok => true
21. // myValue => 123
22. }

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

InstanceSet / InstanceGet

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

1. type User struct {
2. gorm.Model
3. CreditCard CreditCard
4. // ...
5. }

7. func (u *User) BeforeCreate(tx *gorm.DB) error {
8. myValue, ok := tx.InstanceGet("my_value")
9. // ok => true
10. // myValue => 123
11. }

13. type CreditCard struct {
14. gorm.Model
15. // ...
16. }

18. // 在创建关联时,GORM 创建了一个新 `*Statement`,所以它不能读取到其它实例的设置
19. func (card *CreditCard) BeforeCreate(tx *gorm.DB) error {
20. myValue, ok := tx.InstanceGet("my_value")
21. // ok => false
22. // myValue => nil
23. }

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