# 設置
GORM 提供了 `Set`, `Get`, `InstanceSet`, `InstanceGet` 方法來允許用戶傳值給 [鉤子](http://v2.gorm.io/zh_CN/docs/hooks.html) 或其他方法
Gorm 中有一些特性用到了這種機制,如遷移表格時傳遞表格選項。
```go
// 創建表時添加表后綴
db.Set("gorm:table_options", "ENGINE=InnoDB").AutoMigrate(&User{})
```
## Set / Get
使用 `Set` / `Get` 傳遞設置到鉤子方法,例如:
```go
type User struct {
gorm.Model
CreditCard CreditCard
// ...
}
func (u *User) BeforeCreate(tx *gorm.DB) error {
myValue, ok := tx.Get("my_value")
// ok => true
// myValue => 123
}
type CreditCard struct {
gorm.Model
// ...
}
func (card *CreditCard) BeforeCreate(tx *gorm.DB) error {
myValue, ok := tx.Get("my_value")
// ok => true
// myValue => 123
}
myValue := 123
db.Set("my_value", myValue).Create(&User{})
```
## InstanceSet / InstanceGet
使用 `InstanceSet` / `InstanceGet` 傳遞設置到 `*Statement` 的鉤子方法,例如:
```go
type User struct {
gorm.Model
CreditCard CreditCard
// ...
}
func (u *User) BeforeCreate(tx *gorm.DB) error {
myValue, ok := tx.InstanceGet("my_value")
// ok => true
// myValue => 123
}
type CreditCard struct {
gorm.Model
// ...
}
// 在創建關聯時,GORM 創建了一個新 `*Statement`,所以它不能讀取到其它實例的設置
func (card *CreditCard) BeforeCreate(tx *gorm.DB) error {
myValue, ok := tx.InstanceGet("my_value")
// ok => false
// myValue => nil
}
myValue := 123
db.InstanceSet("my_value", myValue).Create(&User{})
```