Laravel 5.3 查询以从通过外键连接的 4 个表中获取结果
Laravel 5.3 query to get results from 4 tables which has connections via Foreign Key
我正在使用 Laravel 5.3。我有 4 tables。
默认 Users
table。 Departments
, Position
, Employees
tables.
Users
table 有 ID | Email | Password
Departments
table 有 ID | Department | User_Id
- 这里 User_Id
是外键来自 Users
table 的 ID
Positions
table 有 ID | Position | Department_Id
- 这里 Department_Id
是外键来自 Departments
table 的 ID
Employees
table 有 ID | Employee | Position_Id
- 这里 Position_Id
是外键来自 Positions
table 的 ID
用户可以有多个Departments
。 Departments
可以有多个Positions
,Positions
可以有多个Employees
。因此,如果用户不同,我如何从该用户创建的所有 4 table 中检索所有数据?
您可以使用 nested eager loading:
$departments = Department::where('user_id', $id)
->with('positions', 'positions.employees')
->get();
另一种方法是构建简单查询:
$departments = Department::where('user_id', $id)->get();
$positions = Position::whereIn('department_id', $departments->pluck('id'));
$employees = Employee::whereIn('position_id', $positions->pluck('id'));
我正在使用 Laravel 5.3。我有 4 tables。
默认 Users
table。 Departments
, Position
, Employees
tables.
Users
table 有 ID | Email | Password
Departments
table 有 ID | Department | User_Id
- 这里 User_Id
是外键来自 Users
table 的 ID
Positions
table 有 ID | Position | Department_Id
- 这里 Department_Id
是外键来自 Departments
table 的 ID
Employees
table 有 ID | Employee | Position_Id
- 这里 Position_Id
是外键来自 Positions
table 的 ID
用户可以有多个Departments
。 Departments
可以有多个Positions
,Positions
可以有多个Employees
。因此,如果用户不同,我如何从该用户创建的所有 4 table 中检索所有数据?
您可以使用 nested eager loading:
$departments = Department::where('user_id', $id)
->with('positions', 'positions.employees')
->get();
另一种方法是构建简单查询:
$departments = Department::where('user_id', $id)->get();
$positions = Position::whereIn('department_id', $departments->pluck('id'));
$employees = Employee::whereIn('position_id', $positions->pluck('id'));