the_coder_inside
the_coder_inside

Reputation: 261

Gorm with golang: Preload does not work as expected

I have following structs

type Employee struct {
    EmployeeID        int64  `gorm:"primary_key;column:employee_id"`
    EmployeeCode      string `gorm:"column:employee_code"`
    FirstName         string `gorm:"column:first_name"`
    LastName          string `gorm:"column:last_name"`
    DesignationID     int64  `gorm:"column:designation_id;"`
    Designation       *Designation
}

type Designation struct {
    DesignationID   int64  `gorm:"primary_key;column:designation_id"`
    DesignationName string `gorm:"column:designation_name"`
}

func GetEmployee(id int64) (*Employee, error) {
    db := connection.GetConn() //get connection
    defer db.Close()  

    employee := &Employee{}
    err := db.Model(employee).Preload("Designation").Find(employee).Error
    return employee, err
 }

In the tables I have following records:

employee :
employee_id | employee_code | first_name | last_name | designation_id
          1 |  EMP1         |  Raj       |  Mane     | 1

designation:
designation_id | designation_name
             1 |  Engineer      

The employee.designation_id is marked as foreign key referring to designation table

When I call the function GetEmployee, it returns error saying can't preload field Designation for model.Employee

I have referred many questions related to Preload but none of the solution has worked. I think only difference between the other working cases is the primary id column name. Can anyone suggest what is happening and what am I missing here?

Upvotes: 0

Views: 1862

Answers (2)

Prinkal Kumar
Prinkal Kumar

Reputation: 3316

Just simply change your variable name from DesignationID to DesignationDesignationID. It will work. As per document ForignKey must be TABLE_NAME + PRIMARY_KEY_NAME so here table is DESIGNATION and primary key DESIGNATIONID

type Employee struct {
    EmployeeID        int64  `gorm:"primary_key;column:employee_id"`
    EmployeeCode      string `gorm:"column:employee_code"`
    FirstName         string `gorm:"column:first_name"`
    LastName          string `gorm:"column:last_name"`
    DesignationDesignationID     int64 
    Designation       *Designation
}

type Designation struct {
    DesignationID   int64  `gorm:"primary_key;`
    DesignationName string `gorm:"column:designation_name"`
}

Upvotes: 0

Eklavya
Eklavya

Reputation: 18410

In GORM default foreign key uses owner’s type name plus its primary key. GORM provides a way to customize the foreign key, for example:

type Employee struct {
    EmployeeID        int64  `gorm:"primary_key;column:employee_id"`
    EmployeeCode      string `gorm:"column:employee_code"`
    FirstName         string `gorm:"column:first_name"`
    LastName          string `gorm:"column:last_name"`
    DesignationID     int64  `gorm:"column:designation_id;"`
    Designation       *Designation `gorm:"foreignkey:DesignationID"`
}

Upvotes: 2

Related Questions