設定

GORM 提供 SetGetInstanceSetInstanceGet 方法,讓使用者可以將值傳遞給 hooks 或其他方法

GORM 使用這項功能來執行某些功能,例如在遷移資料表時傳遞建立資料表選項。

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

設定 / 取得

使用 Set / Get 將設定傳遞給 hooks 方法,例如

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 的 hooks 方法,例如

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

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

白金贊助商

金牌贊助商

白金贊助商

金牌贊助商