第七色在线视频,2021少妇久久久久久久久久,亚洲欧洲精品成人久久av18,亚洲国产精品特色大片观看完整版,孙宇晨将参加特朗普的晚宴

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

一對多關(guān)聯(lián)從一張表中獲取數(shù)據(jù)

一對多關(guān)聯(lián)從一張表中獲取數(shù)據(jù)

Go
搖曳的薔薇 2022-11-23 19:21:50
我是 Golang 和 Gorm 的新手,我找不到答案。在休息 api 中,我希望我的 json 帶有來自一個表關(guān)系的值。type Product struct {    gorm.Model       Name             string           Description      string           Weight           string    TypeID           uint}type Type struct {    ID                   string         `gorm:"primaryKey;"`    Name                 string    Product              []Product}我希望我的產(chǎn)品 json 帶有來自類型的 ID 和名稱。但這不起作用。var product Productid:=1db.Preload("Type").First(&product, id)我必須在結(jié)構(gòu)中做這樣的事情嗎?type Product struct {    gorm.Model       Name             string           Description      string           Weight           string    Type             Type }
查看完整描述

1 回答

?
精慕HU

TA貢獻1845條經(jīng)驗 獲得超8個贊

如果要將 and 加載Type.ID到Type.NameandProduct.ID中Product.Name,則需要專門從兩個表中選擇字段:


var product Product

id:=1

db.Joins("JOIN types ON types.id = products.type_id"). Select("types.id, types.name, products.description, products.weight, products.type_id").First(&product, id)

如果要Type在結(jié)構(gòu)中將字段分隔成單獨的字段,則Product需要進行以下更改:


type Product struct {

    gorm.Model   

    Name             string       

    Description      string       

    Weight           string

    TypeID           uint

    Type             Type 

}


var product Product

id:=1

db.Preload("Type").First(&product, id)

在這里,所有Type字段都將加載到Product.Type字段中。


查看完整回答
反對 回復 2022-11-23
  • 1 回答
  • 0 關(guān)注
  • 129 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯(lián)系客服咨詢優(yōu)惠詳情

幫助反饋 APP下載

慕課網(wǎng)APP
您的移動學習伙伴

公眾號

掃描二維碼
關(guān)注慕課網(wǎng)微信公眾號