我是 GOlang 和 GORM 的新手,我对如何使用 GORM 进行多表连接有些困惑。
Example:
Tables:
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
Query
SELECT * FROM department d, employee e, employeeContact ec WHERE d.id = e.department_id and e.id = ec.employee_id
如何使用 GORM 进行上述查询?
我一直在这里寻找解决方案,但由于我已经自己弄清楚了,所以我也想将其发布在这里。我的查询有点不同,我只连接了 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, ""
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)