英文:
GoLang How to load nested objects using GORM
问题
嗨,让我们假设我有以下格式的3个结构体:
type Employee struct {
Id int
Name string
CompanyId int `gorm:"column:companyId"`
Company Company `gorm:"foreignKey:CompanyId"`
}
type Company struct {
Id int
CompanyName string
OwnerId int `gorm:"column:owner"`
Owner Owner `gorm:"foreignKey:OwnerId"`
}
type Owner struct {
Id int
Name string
Age int
Email string
}
func (E Employee) GetAllEmployees() ([]Employee, error) {
Employees := []Employee{}
db.Preload("Company").Find(&Employees)
}
这里我正在获取Owner的默认值。给出的示例是为了描述我想要实现的目标。
我需要一种方法,在加载Employees时同时加载Owner结构体及其值。
对于这个问题,我有以下建议:
-
使用
Preload
方法预加载Owner结构体。在GetAllEmployees
函数中,你可以使用Preload("Company.Owner")
来预加载Company和Owner结构体。 -
确保数据库中的Employee表与Company表和Owner表之间有正确的关联关系。你可以使用
gorm:"foreignKey:OwnerId"
来指定Owner表的外键。 -
确保Owner结构体的字段名与数据库表中的列名一致。你可以使用
gorm:"column:owner"
来指定Owner表中的列名。
希望这些建议对你有帮助!如果你有任何其他问题,请随时提问。
英文:
Hi let's say that I have 3 Structs in the following format
type Employee struct {
Id int
Name string
CompanyId int `gorm:"column:companyId"`
Company Company `gorm:"foreignKey:CompanyId"`
}
type Company struct {
Id int
CompanyName string
OwnerId `gorm:"column:owner"`
Owner Owner `gorm:"foreignKey:OwnerId"`
}
type Owner struct {
Id int
Name string
Age int
Email string
}
func (E Employee) GetAllEmployees() ([]Employee, error) {
Employees := []Employee
db.Preload("Company").Find(&Employees)
}
// -- -- There response will be like
[
{
id: 1
name: "codernadir"
company: {
id: 5
company_name: "Company"
owner: {
id 0
Name ""
Age 0
Email ""
}
}
}
]
here I'm getting Owner values with the default values.
the given examples are for describing what I'm trying to reach.
I need a way how to load the Owner struct with its values when I load the Employees?
any suggestions will be appreciated and thanks in advance
答案1
得分: 0
你可以使用gorm:"embedded"
标签:
type Employee struct {
Id int
Name string
CompanyId int `gorm:"column:companyId"`
Company Company `gorm:"embedded"`
}
type Company struct {
Id int
CompanyName string
OwnerId int `gorm:"column:owner"`
Owner Owner `gorm:"embedded"`
}
type Owner struct {
Id int
Name string
Age int
Email string
}
英文:
You can use the gorm:"embedded"
tag:
type Employee struct {
Id int
Name string
CompanyId int `gorm:"column:companyId"`
Company Company `gorm:"embedded"`
}
type Company struct {
Id int
CompanyName string
OwnerId `gorm:"column:owner"`
Owner Owner `gorm:"embedded"`
}
type Owner struct {
Id int
Name string
Age int
Email string
}
答案2
得分: 0
这是我找到的从嵌套结构中加载嵌套对象的解决方案:
db.Preload("Company").Preload("Company.Owner").Find(&Employees)
英文:
this is what I found as a solution to load the nested objects from embedded structs
db.Preload("Company").Preload("Company.Owner").Find(&Employees)
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论