I have this two structs on my Go app
我的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"`
}
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.
当您使用Preload函数时,您向它传递要为其加载数据的字段的名称。
In your case, it should look like this (because your field in the Customer
struct is named Address
):
在您的例子中,它应该如下所示(因为您的Customer结构中的字段名为Address):
u.db.Preload("Address").Find(&customers)
You can check out the documentation for more details.
您可以查看文档以了解更多详细信息。
I have these two entities
, UserAccount
with an ID field as a primary key, and UserLoginData
with a userId
foreign key. I want to query UserLoginData by email
and retrieve all the values of UserAccount
with the corresponding userId
. I've done it as shown below. Although I can fetch the fields from UserAccount
, I can't access some information like firstName
and userName
for UserAccount
我有两个实体,UserAccount和UserLoginData,UserAccount使用ID字段作为主键,UserLoginData使用UserID外键。我想通过电子邮件查询UserLoginData,并检索具有相应UserID的UserAccount的所有值。我已经这样做了,如下所示。虽然我可以从UserAccount获取字段,但我无法访问UserAccount的FirstName和UserName等信息
// entities
type UserAccount struct {
gorm.Model
FirstName string
LastName string
UserName string
Gender string
Avatar string
DateOfBirth string
}
type UserLoginData struct {
gorm.Model
UserID uint
UserAccount UserAccount `gorm:"foreignKey:UserID"`
PasswordHash string
}
// in repository
var user entity.UserLoginData
r.db.Preload("UserAccount").Where("email = ?", email).First(&user)
更多回答
我是一名优秀的程序员,十分优秀!