I'm newbie of Golang and GORM. I get some issues on it. How can I get the inside struct value? (Like a nested struct in golang), I tried but, i didn't get actual result.
I have three structs
Department Struct
type Department struct {
gorm.Model
DepartmentName string
DeptCode string
Employee Employee //Employee struct
}
Employee struct
type Employee struct {
gorm.Model
EmpId string
EmpName string
DepartmentID uint //Department id
EmployeeContact []EmployeeContact //Array of Employee contact
}
Employee Contact
type EmployeeContact struct {
gorm.Model
ContactType string
ContacText string
EmployeeID uint //Employee Id
}
Relationship
# Department is a Parent of Employee.
# Employee is a Parent of Employee contacts.
I used GORM (Joins)
var departmentStruct model.Department
var employeeStruct model.Employee
db.Debug().Model(&departmentStruct).Joins("JOIN employees ON employees.department_id = departments.id").Joins("JOIN employee_contacts ON employee_contacts.employee_id = employees.id").Select("employees.id,departments.department_name,departments.dept_code,employees.emp_id,employees.emp_name,employee_contacts.contact_type").Scan(&employeeStruct)
res1B, _ := json.Marshal(employeeStruct)
fmt.Fprintln(w, string(res1B))
It will be return the output
is
{
"ID":1,
"EmpId":"001",
"EmpName":"samsung",
"DepartmentID":0,
"EmployeeContact":{ //It will be return empty
"ID":0,
"CreatedAt":"0001-01-01T00:00:00Z",
"UpdatedAt":"0001-01-01T00:00:00Z",
"DeletedAt":null,
"ContactType":"",
"ContacText":"",
"EmployeeID":0
}
}
I need, When I pass Employee id
it will be return like given below format
{
"ID":1,
"EmpId":"001",
"EmpName":"samsung",
"Department":{
"ID":1,
"CreatedAt":"0001-01-01T00:00:00Z",
"UpdatedAt":"0001-01-01T00:00:00Z",
"DeletedAt":null,
"DepartmentName":"Software Analyst",
"deptCode":"SA"
},
"EmployeeContact":[
{
"ID":1,
"CreatedAt":"0001-01-01T00:00:00Z",
"UpdatedAt":"0001-01-01T00:00:00Z",
"DeletedAt":null,
"ContactType":"Home",
"ContacText":"1234567890",
"EmployeeID":1
},
{
"ID":2,
"CreatedAt":"0001-01-01T00:00:00Z",
"UpdatedAt":"0001-01-01T00:00:00Z",
"DeletedAt":null,
"ContactType":"Office",
"ContacText":"0123456789",
"EmployeeID":1
}
]
}
Any one can teach me?. How can I achieve it. Thanks.