嗨,假设我有 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 "" } } } ]
这里我得到了具有默认值的所有者值。 给出的示例用于描述我想要达到的目标。
我需要一种方法,如何在加载员工时加载所有者结构及其值?
如有任何建议,我们将不胜感激,并提前致谢
P粉6429205222024-03-28 11:06:30
您可以使用 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 }
P粉1487820962024-03-28 00:24:16
这是我发现的从嵌入式结构加载嵌套对象的解决方案
db.Preload("Company").Preload("Company.Owner").Find(&Employees)