Laravel 5.3查询从4个表中获得结果,这些表通过外键连接

Xah*_*mal 6 laravel laravel-5 laravel-5.3

我正在使用Laravel 5.3.我有4张桌子.默认Users表.Departments,Position,Employees表.

Users 表有 ID | Email | Password

Departmentstable has ID | Department | User_Id- 这User_Id是外键来自Userstable'sID

Positionstable has ID | Position | Department_Id- 这Department_Id是外键来自Departmentstable'sID

Employeestable has ID | Employee | Position_Id - 这Position_Id是外键来自Positionstable'sID

用户可以拥有多个Departments.Departments可以有多个Positions,Positions可以有多个Employees.因此,如果用户不同,我如何从该用户创建的所有4个表中检索所有数据?

Ale*_*nin 3

您可以使用嵌套的预加载

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

另一种方法是构建简单的查询:

$departments = Department::where('user_id', $id)->get();
$positions = Position::whereIn('department_id', $departments->pluck('id'));
$employees = Employee::whereIn('position_id', $positions->pluck('id'));
Run Code Online (Sandbox Code Playgroud)