嗨,假设我有 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 `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 ""
}
}
}
]
这里我得到了具有默认值的所有者值。 给出的示例用于描述我想要达到的目标。
我需要一种方法,如何在加载员工时加载所有者结构及其值?
如有任何建议,我们将不胜感激,并提前致谢
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号
您可以使用
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 `gorm:"column:owner"` Owner Owner `gorm:"embedded"` } type Owner struct { Id int Name string Age int Email string }这是我发现的从嵌入式结构加载嵌套对象的解决方案
db.Preload("Company").Preload("Company.Owner").Find(&Employees)