我是Golang和GORM的新手 . 我有一些问题 . 我怎样才能获得内部结构值? (就像golang中的嵌套结构一样),我试过但是,我没有得到实际的结果 .
我有三个结构
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是员工的父母 .
#Employee是员工联系人的父母 .
我用了GORM(加入)
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))
它将返回 output
{
"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
}
}
我需要,当我通过Employee id
时,它会像下面给出的格式一样返回
{
"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
}
]
}
任何人都可以教我吗?我怎样才能实现它 . 谢谢 .
1 回答
首先,您可能希望您的员工模型喜欢这样
然后这个预加载就可以了
并且他们的员工参数应该包含系统中具有预加载关系的所有员工的列表