首页 文章

如何在GORM中多个表连接

提问于
浏览
0

我是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

    我在这里寻找解决方案,但既然我已经自己想出来了,我也想在这里发布 . 我的查询有点不同,我只加入了两张 table ,但我认为这个也应该有效 .

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

相关问题