首页 > 解决方案 > GORM 以一对一的关系从两个表中获取数据

问题描述

我的 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
}

标签: gogo-gorm

解决方案


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

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

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

您可以查看文档以获取更多详细信息。


推荐阅读