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

How to Perform Multiple Table Joining in GORM?

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2024-10-24 14:42:02435browse

How to Perform Multiple Table Joining in GORM?

Multiple Table Joining in GORM

Joining multiple tables in GORM involves establishing relationships between models that represent different tables in the database. The GORM syntax for multiple table joins leverages the Joins() method to specify the join criteria.

Example:

Consider the following example where we have three tables:

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

The following query retrieves data from all three tables based on the specified join conditions:

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

To perform this query using GORM, we can use the following code:

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

In this code:

  • db.Table("employee") specifies the primary table for the query.
  • Select() defines the fields to be retrieved from the joined tables.
  • Joins() establishes the join criteria for each table.
  • Find() retrieves the results into the results variable.

The above is the detailed content of How to Perform Multiple Table Joining 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