如何在gorm中获取结构(内部结构)值

时间:2018-07-11 13:54:29

标签: go go-gorm

我是Golang和GORM的新手。我遇到了一些问题。我如何获得内部结构值? (就像golang中的嵌套结构一样),我尝试过,但没有得到实际结果。

我有三个结构

部门结构

type Department struct {
    gorm.Model
    DepartmentName string
    DeptCode       string
    Employee       Employee //Employee struct
}

员工结构

type Employee struct {
    gorm.Model
    EmpId           string
    EmpName         string
    DepartmentID    uint //Department id
    EmployeeContact []EmployeeContact //Array of Employee contact
}

员工联系人

type EmployeeContact struct {
    gorm.Model
    ContactType string
    ContacText  string
    EmployeeID  uint //Employee Id
}

关系

#部门是雇员的父母。

#Employee是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 个答案:

答案 0 :(得分:1)

首先,您可能希望您的员工模型喜欢这个

type Employee struct {
    gorm.Model
    EmpId           string
    EmpName         string
    Department      Department
    DepartmentID    uint //Department id
    EmployeeContact []EmployeeContact //Array of Employee contact
}

然后这个预加载就可以解决问题

var employee []model.Employee

err := db.Preload("Department").Preload("EmployeeContact").Find(&employee).Error

并且他们的employee参数应该具有系统中所有具有预加载关系的雇员的列表