如何在GORM中进行多个表联接

时间:2018-07-09 11:17:09

标签: 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

查询

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

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

1 个答案:

答案 0 :(得分:0)

我一直在这里寻找解决方案,但是由于我已经自己弄清楚了,所以我也想在这里发布。我的查询有点不同,我只联接了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, ""
}
相关问题