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. }
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
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. }
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. // When creating associations, GORM creates a new `*Statement`, so can't read other instance's settings
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{})
