Home >Backend Development >Golang >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:
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:
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!