【发布时间】: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
}
【问题讨论】: