search

Home  >  Q&A  >  body text

GoLang method to load nested objects using GORM

Hi, let's say I have 3 structures 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 got the owner value with default value. The example given is used to describe what I want to achieve.

I need a way how to load the owner structure and its value when loading employees?

Any suggestions would be greatly appreciated and thanks in advance

P粉448346289P粉448346289240 days ago492

reply all(2)I'll reply

  • P粉642920522

    P粉6429205222024-03-28 11:06:30

    You can use gorm:"embedded" Tags:

    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
    }

    reply
    0
  • P粉148782096

    P粉1487820962024-03-28 00:24:16

    This is the solution I found for loading nested objects from embedded structures

    db.Preload("Company").Preload("Company.Owner").Find(&Employees)
    

    reply
    0
  • Cancelreply