亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

Golang Gorm 不從關聯表中檢索數據

Golang Gorm 不從關聯表中檢索數據

Go
收到一只叮咚 2022-12-05 17:13:42
我正在開發一個使用 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


查看完整回答
反對 回復 2022-12-05
  • 1 回答
  • 0 關注
  • 201 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號