我是 Golang 和 Gorm 的新手,我找不到答案。在休息 api 中,我希望我的 json 帶有來自一個表關系的值。
type Product struct {
gorm.Model
Name string
Description string
Weight string
TypeID uint
}
type Type struct {
ID string `gorm:"primaryKey;"`
Name string
Product []Product
}
我希望我的產品 json 帶有來自型別的 ID 和名稱。但這不起作用。
var product Product
id:=1
db.Preload("Type").First(&product, id)
我必須在結構中做這樣的事情嗎?
type Product struct {
gorm.Model
Name string
Description string
Weight string
Type Type
}
uj5u.com熱心網友回復:
如果要加載Type.IDandType.Name到Product.IDand 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中的單獨欄位,則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欄位中。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/447723.html
上一篇:按Enter時分配的默認值
