嗨,假設我有 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)