如何在 GORM 中进行多表连接

问题描述 投票:0回答:3

我是 GOlang 和 GORM 的新手,我对如何使用 GORM 进行多表连接有些困惑。

示例:

表格:

Department - Fields (gorm.Modal, dep_name)
Employee - Fields (gorm.Modal, emp_id, emp_name, department_id) //employee is department table child 
EmployeeContact - Fields (gorm.Modal, employee_id, emp_contact_no)//Employee contact table is employee table child

查询

SELECT * FROM department d, employee e, employeeContact ec WHERE d.id = e.department_id and e.id = ec.employee_id

如何使用 GORM 进行上述查询?

go go-gorm
3个回答
6
投票

我一直在这里寻找解决方案,但由于我已经自己弄清楚了,所以我也想将其发布在这里。我的查询有点不同,我只加入了 2 个表,但我认为这个也应该有效。

if err := db.Table("employee").Select("department.id, employee.department_id, employeeContact.employee_id").Joins("JOIN department on department.id = employee.department_id").Joins("JOIN employeeContact on employeeContact.id = employee.id").Find(&results).Error; err != nil {
    return err, ""
}

0
投票

您可以使用

Preload
但请注意,预加载并未针对此查询进行优化

首先,假设已经定义了模型:

type Department struct{
    gorm.Modal
    DepName string
    Employees *[]Employee
}

type Employee struct{
    gorm.Modal
    EmpId int
    EmpName string
    DepartmentId int
    Department Department
}

type EmployeeContact struct{
    gorm.Modal
    EmpId int
    EmpContactNo string
}

然后我们可以使用这个例子进行多个连接:

var department Department
db.
Model(&Department{}).
Where("DepName = ?", form.DepName).
Preload("Employees", func(tx *gorm.DB) *gorm.DB {
    return tx.Preload("Department")
}).Find(&department)

0
投票

您可以使用预加载

db.Preload("Department").
    Preload("Employee.EmployeeContact").
    Where(<condition>).
    Find(&variable)

我认为文档非常简单:https://gorm.io/docs/preload.html#Preload.

我希望这有帮助

© www.soinside.com 2019 - 2024. All rights reserved.