如何在 GORM 中连接多个表

Uda*_*mar 4 go go-gorm

我是 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
Run Code Online (Sandbox Code Playgroud)

询问

SELECT * FROM department d, employee e, employeeContact ec WHERE d.id = e.department_id and e.id = ec.employee_id
Run Code Online (Sandbox Code Playgroud)

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

小智 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, ""
}
Run Code Online (Sandbox Code Playgroud)

  • 我们不能使用PreLoad()吗? (6认同)