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

huangapple go评论82阅读模式
英文:

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("Address").Find(&customers)
	return customers, nil
}

以上代码中的Preload("Address")可以用来预加载关联的地址数据。这样,当你查询顾客数据时,地址数据也会被同时获取到。

英文:

I have this two structs on my Go app

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"`
}

I'm using Angular at my front-end, so it would be very practical if I don't have to make two requests to get the Customer then the Address.

I searched in here but couldn't find an example for a one to one relationship, is there a way to make this query get not only the customer data, but also the address?

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

答案1

得分: 1

当你使用Preload函数时,你需要传递要加载数据的字段的名称。

在你的情况下,应该像这样写(因为你在Customer结构体中的字段名为Address):

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

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

英文:

When you use the Preload function, you pass it the name of the field you want to load the data for.

In your case, it should look like this (because your field in the Customer struct is named Address):

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

You can check out the documentation for more details.

huangapple
  • 本文由 发表于 2021年5月22日 09:36:25
  • 转载请务必保留本文链接:https://go.coder-hub.com/67645372.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定