Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Laravel 5.3 query to get results from 4 tables which has connections via Foreign Key

I'm using Laravel 5.3. I've 4 tables. Default Users table. Departments, Position, Employees tables.

Users table has ID | Email | Password

Departments table has ID | Department | User_Id - Here User_Id is foreign key comes from Users table's ID

Positions table has ID | Position | Department_Id - Here Department_Id is foreign key comes from Departments table's ID

Employees table has ID | Employee | Position_Id - Here Position_Id is foreign key comes from Positions table's ID

User can have multiple Departments. Departments can have multiple Positions, Positions can have multiple Employees. So, if user is different, how can i retrieve all data from all 4 tables which that user had created?

like image 552
Xahed Kamal Avatar asked Dec 25 '16 22:12

Xahed Kamal


1 Answers

You can use nested eager loading:

$departments = Department::where('user_id', $id)
    ->with('positions', 'positions.employees')
    ->get();

Another way is to build simple queries:

$departments = Department::where('user_id', $id)->get();
$positions = Position::whereIn('department_id', $departments->pluck('id'));
$employees = Employee::whereIn('position_id', $positions->pluck('id'));
like image 159
Alexey Mezenin Avatar answered Sep 20 '22 13:09

Alexey Mezenin