我正在开发一个使用 Gorm 和 MySQL 的 Gin 应用程序。为了belongs to在 Gorm 模型中定义关系,您必须执行以下操作(示例来自 Gorm 文档):// `User` belongs to `Company`, `CompanyID` is the foreign keytype 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}知道那里发生了什么吗?
1 回答
桃花长相依
TA贡献1860条经验 获得超8个赞
将数据保存到数据库的代码是什么样的?
我猜你可能需要使用这样的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
- 1 回答
- 0 关注
- 327 浏览
添加回答
举报
0/150
提交
取消
