4 回答

TA貢獻1878條經驗 獲得超4個贊
筆記!
從 gorm 2.0 開始,這不再是必需的
解決辦法是在遷移數據庫的時候加入這一行:
db.Model(&models.UserInfo{}).AddForeignKey("u_id",?"t_user(id)",?"RESTRICT",?"RESTRICT")

TA貢獻1824條經驗 獲得超5個贊
我發現以下代碼無需執行任何自定義遷移代碼即可正確創建外鍵;只是平常的AutoMigrate。
type Account struct {
ID uint `gorm:"primary_key"`
}
type Transaction struct {
ID uint `gorm:"primary_key"`
AccountID uint
Account Account `gorm:"constraint:OnUpdate:CASCADE,OnDelete:CASCADE;"`
}
我正在使用“Gorm 2.0”,它是gorm.io/gorm v1.23.3.

TA貢獻1842條經驗 獲得超13個贊
閱讀https://gorm.io/docs/belongs_to.html中的屬于關系 此外,這里有一個很好的例子: https: //medium.com/@the.hasham.ali/how-to-use-uuid -key-type-with-gorm-cc00d4ec7100
// User is the model for the user table.
type User struct {
Base
SomeFlag bool `gorm:"column:some_flag;not null;default:true"`
Profile Profile
}// Profile is the model for the profile table.
type Profile struct {
Base
Name string `gorm:"column:name;size:128;not null;"`
UserID uuid.UUID `gorm:"type:uuid;column:user_foreign_key;not null;"`
}

TA貢獻1847條經驗 獲得超7個贊
我們可以在最新版本中使用添加外鍵約束CreateConstraint。
示例:假設我們有兩個實體
type User struct {
gorm.Model
CreditCards []CreditCard
}
type CreditCard struct {
gorm.Model
Number string
UserID uint
}
現在為用戶和信用卡創建數據庫外鍵
db.Migrator().CreateConstraint(&User{}, "CreditCards")
db.Migrator().CreateConstraint(&User{}, "fk_users_credit_cards")
轉換為 Postgres 的以下 SQL 代碼:
ALTER TABLE `credit_cards` ADD CONSTRAINT `fk_users_credit_cards` FOREIGN KEY (`user_id`) REFERENCES `users`(`id`)
- 4 回答
- 0 關注
- 406 瀏覽
添加回答
舉報