2016-12-25 72 views
6

我使用的是Laravel 5.3。我有4張桌子。 默認Users表。 Departments,Position,Employees表。Laravel 5.3查詢從4個表中獲得結果,通過外鍵連接

Users表有ID | Email | Password

Departments表有ID | Department | User_Id - 在這裏User_Id是外鍵來自Users表的ID

Positions表已經ID | Position | Department_Id - 在這裏Department_Id是外鍵來自Departments表的ID

Employees表有ID | Employee | Position_Id - 在這裏Position_Id是外鍵來自Positions表的ID

用戶可以有多個DepartmentsDepartments可以有多個PositionsPositions可以有多個Employees。所以,如果用戶不同,我如何檢索該用戶創建的所有4個表中的所有數據?

回答

3

您可以使用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')); 
+0

是什麼你的答案,這之間的區別 - http://stackoverflow.com/a/ 29166530/3866364 我試過這樣,但不能正確創建關係。 –

+0

你是什麼意思的差異?如果您的關係不起作用,請發佈另一個問題並添加您的關係代碼和外鍵的確切名稱(區分大小寫)。 –

+0

對不起,我感到困惑。我的意思是,你的答案只有查詢。但在上面評論的其他問題的答案中,使用了Model(用於例如OneToMany,ManyToOne等)。那麼,使用像urs這樣的查詢或使用Modal關係的好處是什麼? –

相關問題