go - 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
}
解决方案
当您使用该Preload
函数时,您将要为其加载数据的字段的名称传递给它。
在您的情况下,它应该如下所示(因为您在Customer
结构中的字段名为Address
):
u.db.Preload("Address").Find(&customers)
您可以查看文档以获取更多详细信息。
推荐阅读
- javascript - 使用 javascript 将数据添加到 Json 文件
- c# - IdentityServer4 Refresh Token:如何确定过期时间?
- reactjs - React 如何将参数传递给函数
- amazon-web-services - 为 AWS::Lambda::Function 中的环境变量设置 Fn::ImportValue
- c++ - 使用两个 for 循环生成以下星号
- python - 根据条件和现有日期列和时间增量列创建新日期列
- java - 将类型泛化为 Java 中的类型系统
- java - 我正在尝试解析一个文本文件以计算唯一字符串的数量并打印有关这些字符串的一些信息
- search - Prolog - 给定不同的旅行模式,计算 2 个地点之间的最快旅行
- html - 如何添加多个相互停止的音频播放按钮?