CoderNadir
CoderNadir

Reputation: 11

GoLang How to load nested objects using GORM

Hi let's say that I have 3 Structs 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'm getting Owner values with the default values. 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

Upvotes: 1

Views: 941

Answers (3)

Sharath B Naik
Sharath B Naik

Reputation: 1392

Answer is too late, but it is working by using this keyword for nested object from SQL/PSQL. No need to mention foreign key constraint in Go Struct when working with GORM.

gorm:"serializer:json"

E.g.

type User struct {
    ID         string      `json:"id"`
    Name       string      `json:"name"`
    Roles      []string    `json:"roles" gorm:"serializer:json"`
    Educations []Education `json:"educations" gorm:"serializer:json"`
}

type Education struct {
    ID    string   `json:"id"`
    Title string   `json:"title"`
    Tags  []string `json:"tags" gorm:"serializer:json"`
}

Upvotes: 0

CoderNadir
CoderNadir

Reputation: 11

this is what I found as a solution to load the nested objects from embedded structs

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

Upvotes: 0

Leonardo
Leonardo

Reputation: 1

You can use the gorm:"embedded" tag:

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
}

Upvotes: 0

Related Questions