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

Question

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

Answers 1
Added at 2016-12-25 23:12
Tags
Question

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?

Answers to

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

nr: #1 dodano: 2016-12-25 23:12

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'));
Source Show
◀ Wstecz