設定

GORMは、SetGetInstanceSetInstanceGetメソッドを提供し、ユーザーがフックまたは他のメソッドに値を渡すことを可能にします。

GORMは、テーブルのマイグレーション時にテーブル作成オプションを渡すなど、いくつかの機能にこれを使用します。

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

設定 / 取得

Set / Getを使用して、フックメソッドに設定を渡します。例えば、

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を使用して、現在の*Statementのフックメソッドに設定を渡します。例えば、

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{})

プラチナスポンサー

ゴールドスポンサー

プラチナスポンサー

ゴールドスポンサー