我正在使用gorm,并且我有這個結構,其中表包含一個外鍵引用,然后引用。UserAddressCountry type User struct { ID int `gorm:"column:id; primaryKey; autoIncrement" json:"id"` Address Address AddressID int `gorm:"column:address_id;foreignKey:AddressID;references:ID" json:"address"` } type Address struct { ID int `gorm:"column:ID;primaryKey;autoIncrement;" json:"id"` CountryCode int `gorm:"column:country_code; foreignKey:CountryCode; references:Code" json:"country_code"` Country Country } type Country struct { Code int `gorm:"column:code; primaryKey; autoIncrement" json:"code"` Name string `gorm:"column:name" json:"name"` ContinentName string `gorm:"column:continent_name" json:"continentName"` }照片中解釋的關系:現在,當我使用以下命令返回用戶時: db.Model(&user).Where().First() // or Find()我得到地址,和國家空,像這樣: { ID: 1, AddressID: 2, Address: { // empty address. } }我確實為我創建了重新填充和記錄的函數,類似于以下內容:AddressCountryfunc PopulateUser(user) User { addr = FindAddresByID(user.ID) cntr = FindCountryByCode(addr.Code) addr.Country = cntr user.Address = addr return user}但我的問題:有沒有一個函數可以在不創建函數的情況下為我做到這一點?Gorm在這種情況下,協會可以提供幫助嗎?如果我希望在用戶刪除時刪除地址,我該如何執行此操作?Gorm我試圖自己找到答案,但文檔有點亂。
1 回答

守候你守候我
TA貢獻1802條經驗 獲得超10個贊
文檔顯示了要轉到結構引用的外鍵標記。即,在您的情況下,這些應該在地址和國家/地區,而不是地址ID和國家/地區代碼。像這樣:
type User struct {
Address Address `gorm:"foreignKey:AddressID;references:ID"`
AddressID int `gorm:"column:address_id"`
}
type Address struct {
CountryCode int `gorm:"column:country_code"`
Country Country gorm:"foreignKey:CountryCode; references:Code"`
}
請嘗試使用這些。
為
請在此處查看急切加載
db.Preload("User").Preload("Address").Find(&users)
您可以在列上使用級聯標記。
type User struct {
gorm.Model
Name string
CompanyID int
Company Company `gorm:"constraint:OnUpdate:CASCADE,OnDelete:SET NULL;"`
}
- 1 回答
- 0 關注
- 105 瀏覽
添加回答
舉報
0/150
提交
取消