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
}
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.