2017-05-09 266 views
1

我有一個人桌,人可以在很多部門。Laravel加入雄辯

public function departments() 
    { 
     return $this->belongsTo('App\Models\Departments', 'id'); 
    } 

我有一個部門表,部門有很多人

return $this->hasMany('App\Models\People', 'id', 'department_id'); 

百姓餐桌

-id 
-name 
-title 

各部門表

-id 
-person_id 
-department_id 

person_id是外鍵。

所以,如果我期待所有的人都從部門2人(會計)返回我能做到這一點

$depts = $departments::where('department_id', 2)->get(); 
    foreach($depts as $dept) { 
    // do something 
    } 

但這僅返回其ID。這是一個開始,但我如何做聯合返回名稱和標題?我必須做的foreach或有辦法加入?

回答

1

whereHas將由關係約束查詢:

$departmentId = 2; 

People::whereHas('departments', function($query) use ($departmentId) { 
    return $query->where('id', $departmentId); 
}) 
->get(); 
+0

這是偉大的!謝謝。 – LeBlaireau

2

這應該得到的人,除非我失去了一些東西。

$department = Department::with(['people'])->find(2); 

$people = $department->people;