GORM 从一对一关系的两个表中获取数据

GORM get data from both tables on a one to one relationship

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

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

在你的例子中,它应该看起来像这样(因为你在 Customer 结构中的字段被命名为 Address):

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

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