2017-05-09 267 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;