【问题标题】:GORM get data from both tables on a one to one relationshipGORM 以一对一的关系从两个表中获取数据
【发布时间】:2021-05-22 01:36:25
【问题描述】:

我的 Go 应用中有这两个结构

type Customer struct {
    ID             uint       `json: "id" gorm:"primary_key"`
    Name           string     `json: "name"`
    AddressId      int        `json: "addressId"`
    Address        Address    `json: "address"`
}

type Address struct {
    ID        uint   `json: "id" gorm:"primary_key"`
    ZipCode   string `json: "zipCode"`
    StreetOne string `json: "streetOne"`
    StreetTwo string `json: "streetTwo"`
    City      string `json: "city"`
    State     string `json: "state"`
    Number    string `json: "number"`
}

我在前端使用 Angular,所以如果我不必发出两个请求来获取客户然后是地址,这将是非常实用的。

我在这里搜索但找不到一对一关系的示例,有没有办法让这个查询不仅获取客户数据,还获取地址?

func (u customer) GetCustomers(params string) ([]models.Customer, error) {
    customers := []models.Customer{}
    u.db.Preload("Addresses").Find(&customers)
    return customers, nil
}

【问题讨论】:

    标签: go go-gorm


    【解决方案1】:

    当您使用Preload 函数时,您将要为其加载数据的字段的名称传递给它。

    在您的情况下,它应该如下所示(因为您在 Customer 结构中的字段名为 Address):

    u.db.Preload("Address").Find(&customers)
    

    您可以查看documentation了解更多详情。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2019-01-12
      • 2013-09-28
      • 1970-01-01
      • 2020-05-16
      • 1970-01-01
      • 2017-10-26
      • 2019-01-12
      相关资源
      最近更新 更多