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