Laravel 5.3 query to get results from 4 tables that have foreign key connections

I am using Laravel 5.3. I have 4 tables. The default table is Users . Departments , Position , Employees .

Users table has ID | Email | Password ID | Email | Password

Departments table has an ID | Department | User_Id ID | Department | User_Id ID | Department | User_Id - here User_Id is the foreign key coming from the Users table ID

Positions table has an ID | Position | Department_Id ID | Position | Department_Id ID | Position | Department_Id - here Department_Id is the foreign key from the Departments table ID

Employees table has an ID | Employee | Position_Id ID | Employee | Position_Id ID | Employee | Position_Id - here Position_Id is the foreign key coming from the Positions table ID

A user can have multiple Departments . Departments can have several Positions , Positions can have several Employees . So, if the user is different, how can I get all the data from all 4 tables that this user created?

+6
source share
1 answer

You can use the nested download download :

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

Another way is to create 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')); 
+3
source

Source: https://habr.com/ru/post/1013511/


All Articles