Home  >  Article  >  Backend Development  >  How to Perform Multiple Table Joins in GORM?

How to Perform Multiple Table Joins in GORM?

Barbara Streisand
Barbara StreisandOriginal
2024-10-24 11:44:01948browse

How to Perform Multiple Table Joins in GORM?

Multiple Table Joins with GORM

In GORM, performing multiple table joins is a convenient and straightforward process. Consider the following scenario:

You have three tables: Department, Employee, and EmployeeContact, with the following fields:

  • Department: (gorm.Model, dep_name)
  • Employee: (gorm.Model, emp_id, emp_name, department_id)
  • EmployeeContact: (gorm.Model, employee_id, emp_contact_no)

To query these tables using GORM with a multi-table join, follow these steps:

<code class="go">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, ""
}</code>

By specifying the joined table names and their respective relationships, GORM automatically generates the necessary SQL query. In this example, the following SQL query is generated:

<code class="sql">SELECT * FROM department d, employee e, employeeContact ec WHERE d.id = e.department_id and e.id = ec.employee_id</code>

The Find method fills the results slice with instances of the relevant Go structs, making it easy to access the joined data.

The above is the detailed content of How to Perform Multiple Table Joins in GORM?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn