我正在開發一個使用 Gorm 和 MySQL 的 Gin 應用程式。為了belongs to在 Gorm 模型中定義關系,您必須執行以下操作(示例取自 Gorm 檔案):
// `User` belongs to `Company`, `CompanyID` is the foreign key
type User struct {
gorm.Model
Name string
CompanyID int
Company Company
}
type Company struct {
ID int
Name string
}
這就是我對我的模型所做的:
type Record struct {
Barcode string `json:"barcode" gorm:"size:48;unique;not null" sql:"index"`
Name string `json:"name" gorm:"size:160;unique;not null"`
ArtistID uint `json:"artist_id"`
Artist Artist `gorm:"foreignKey:ArtistID;references:ID"`
CategoryID uint `json:"category_id"`
Category Category `gorm:"foreignKey:CategoryID;references:ID"`
NumOfRecords int `json:"num_of_records" gorm:"not null"`
OriginalReleaseDate *utils.Date `json:"original_release_date" gorm:"default:null;type:date"`
ReissueReleaseDate *utils.Date `json:"reissue_release_date" gorm:"default:null;type:date"`
SideColor *string `json:"side_color" gorm:"default:null"`
BarcodeInRecord *bool `json:"barcode_in_record" gorm:"default=true"`
gorm.Model
}
type Category struct {
Name string `json:"name" gorm:"size:60;unique;not null"`
Description string `json:"description" gorm:"size:120"`
Parent uint `json:"parent" gorm:"default:null"`
Active bool `json:"active" gorm:"default:true"`
gorm.Model
}
type Artist struct {
Name string `json:"name" gorm:"size:120;unique;not null"`
Type string `json:"type" gorm:"default:null"`
CountryOfOrigin string `json:"countryOfOrigin" gorm:"default:null"`
gorm.Model
}
然而,當取回資料時,這兩個關聯并沒有被填充:
{
"data": {
"barcode": "1231231231231292",
"name": "ABCD 12342",
"artist_id": 2,
"Artist": {
"name": "",
"type": "",
"countryOfOrigin": "",
"ID": 0,
"CreatedAt": "0001-01-01T00:00:00Z",
"UpdatedAt": "0001-01-01T00:00:00Z",
"DeletedAt": null
},
"category_id": 9,
"Category": {
"name": "",
"description": "",
"parent": 0,
"active": false,
"ID": 0,
"CreatedAt": "0001-01-01T00:00:00Z",
"UpdatedAt": "0001-01-01T00:00:00Z",
"DeletedAt": null
},
"num_of_records": 2,
"original_release_date": "1965-02-24",
"reissue_release_date": null,
"side_color": null,
"barcode_in_record": null,
"ID": 1,
"CreatedAt": "2022-04-25T12:53:32.275578-04:00",
"UpdatedAt": "2022-04-25T12:53:32.275578-04:00",
"DeletedAt": null
}
}
知道那里發生了什么嗎?
uj5u.com熱心網友回復:
將資料保存到資料庫的代碼是什么樣的?
我猜你可能需要使用這樣的FullSaveAssociations
東西:
DB().Session(&gorm.Session{FullSaveAssociations: true}).Save(&d)
要取回資料,您需要使用 Preloads。
DB().Preload("Artist").Preload("Category").First(&d)
你也可以使用
.Preload(clause.Associations)
加載它們。您可以將其與其他預加載一起使用以更深入地了解。
https://gorm.io/docs/preload.html#content-inner
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/464318.html
