简体   繁体   English

GoLang 如何使用 GORM 加载嵌套对象

[英]GoLang How to load nested objects using GORM

Hi let's say that I have 3 Structs in the following format嗨,假设我有以下格式的 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 ""
      }
    }
  }
]

here I'm getting Owner values with the default values.在这里,我使用默认值获取 Owner 值。 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任何建议将不胜感激并提前感谢

You can use the gorm:"embedded" tag:您可以使用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)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM