【问题标题】:How to multiple table joins in GORM如何在 GORM 中进行多个表连接
【发布时间】:2018-07-09 11:17:08
【问题描述】:

我是 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 进行上述查询?

【问题讨论】:

  • db.Joins() 可用于在 gorm 中执行连接。检查它是否能解决您的问题。
  • 是的,我试过了,但是我怎样才能使用多个表呢? @AnkitDeshpande

标签: go go-gorm


【解决方案1】:

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

【讨论】:

  • 我们不能使用 PreLoad() 吗?
  • 预加载并没有通过一个数据库查询完成执行。它按顺序访问数据库以检索相关记录。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-05-06
  • 2022-01-12
  • 1970-01-01
  • 2023-03-27
  • 2022-06-20
  • 1970-01-01
相关资源
最近更新 更多