一对多关联从一张表中获取数据

我是 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 

}


摇曳的蔷薇
浏览 96回答 1
1回答

精慕HU

如果要将 and 加载Type.ID到Type.NameandProduct.ID中Product.Name,则需要专门从两个表中选择字段:var product Productid:=1db.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 Productid:=1db.Preload("Type").First(&product, id)在这里,所有Type字段都将加载到Product.Type字段中。
打开App,查看更多内容
随时随地看视频慕课网APP