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

How to get the struct (inside struct) values in 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
}

关系

# Department 是 Employee 的父级。

# 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))

它将是 return 而 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 时,它将是 return 如下格式

{

    "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
        }
    ]
}

谁能教教我?。我怎样才能实现它。 谢谢。

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

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

并且他们的员工参数应该包含系统中所有员工的列表以及预加载的关系