登录
首页 >  Golang >  Go问答

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

来源:stackoverflow

时间:2024-02-22 19:33:24 124浏览 收藏

怎么入门Golang编程?需要学习哪些知识点?这是新手们刚接触编程时常见的问题;下面golang学习网就来给大家整理分享一些知识点,希望能够给初学者一些帮助。本篇文章就来介绍《从一个数据表中获取多对一关联的数据》,涉及到,有需要的可以收藏一下

问题内容

我是 golang 和 gorm 的新手,我找不到答案。在 rest 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 
}

正确答案


如果要将type.idtype.name加载到product.idproduct.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 字段中。

好了,本文到此结束,带大家了解了《从一个数据表中获取多对一关联的数据》,希望本文对你有所帮助!关注golang学习网公众号,给大家分享更多Golang知识!

声明:本文转载于:stackoverflow 如有侵犯,请联系study_golang@163.com删除
相关阅读
更多>
最新阅读
更多>
课程推荐
更多>