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

How to Perform Multiple Table Joins with GORM?

Linda Hamilton
Linda HamiltonOriginal
2024-10-24 10:27:29979browse

How to Perform Multiple Table Joins with GORM?

Multiple Table Joins in GORM

Joining tables in GORM allows you to retrieve related data from multiple tables simultaneously. Here's how to perform a join query involving three tables:

Table Structure

Consider the following table structure:

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

Example Query

Suppose you want to retrieve all columns from the three tables where a department's ID matches an employee's department_id, and that employee's ID matches an employeeContact's employee_id:

SQL Query:

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

GORM Equivalent

<code class="go">import (
    "gorm.io/gorm"
)

func MultipleJoinExample(db *gorm.DB) error {
    type Result struct {
        DepartmentID   uint
        EmployeeID    uint
        EmployeeName  string
        EmployeeContactNo string
    }
    var results []Result

    if err := db.Table("employee").Select("department.id, employee.department_id, employeeContact.employee_id, employee.emp_name, employeeContact.emp_contact_no").
        Joins("JOIN department on department.id = employee.department_id").
        Joins("JOIN employeeContact on employeeContact.id = employee.id").
        Find(&results).Error; err != nil {
        return err
    }

    return nil
}</code>

In this example:

  • Table() specifies the table to start the join from.
  • Select() selects the columns to retrieve from each joined table.
  • Joins() establishes the join relationships based on foreign key constraints.
  • Find() retrieves the results into the results slice.

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