Udayakumar
Udayakumar

Reputation: 145

How to multiple table joins in GORM

I'm a newbie for GOlang and GORM, I have some confusion how to multiple table join using GORM.

Example:

Tables:

Department - Fields (gorm.Modal, dep_name)
Employee - Fields (gorm.Modal, emp_id, emp_name, department_id) //employee is department table child 
EmployeeContact - Fields (gorm.Modal, employee_id, emp_contact_no)//Employee contact table is employee table child

Query

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

How to make the above query using GORM?

Upvotes: 4

Views: 23393

Answers (3)

Khalil SAYHI
Khalil SAYHI

Reputation: 3

You can use prelaod

db.Preload("Department").
    Preload("Employee.EmployeeContact").
    Where(<condition>).
    Find(&variable)

the documentation is pretty straight forward i think : https://gorm.io/docs/preload.html#Preload.

i hope this helps

Upvotes: 0

Hamed Naeemaei
Hamed Naeemaei

Reputation: 9638

You can use Preload but notice that the Preload didn't optimize for this query

First, suppose have been defined models:

type Department struct{
    gorm.Modal
    DepName string
    Employees *[]Employee
}

type Employee struct{
    gorm.Modal
    EmpId int
    EmpName string
    DepartmentId int
    Department Department
}

type EmployeeContact struct{
    gorm.Modal
    EmpId int
    EmpContactNo string
}

Then we can use this example for multiple joins:

var department Department
db.
Model(&Department{}).
Where("DepName = ?", form.DepName).
Preload("Employees", func(tx *gorm.DB) *gorm.DB {
    return tx.Preload("Department")
}).Find(&department)

Upvotes: 0

Kirikami
Kirikami

Reputation: 331

I was looking for the solution here but since I already figured it out by myself, I would like to post it here also. My query was a bit different and I was joining only 2 tables but I think this one should work, too.

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, ""
}

Upvotes: 6

Related Questions