Laravel - Eloquent Construction - Group By through Pivot Tab


请帮助我构造一个有说服力的查询。我有这些桌子:
Attendances
id | member_id
1  | 1
2  | 2
3  | 3
4  | 4
5  | 5
Members
id | name
1  | Joe
2  | Jane
3  | David
4  | May
5  | John
Positions
id | position_name
1  | art
2  | singer
3  | dancer
member_position
member_id | position_id
1         | 2 
1         | 1
1         | 3
2         | 1
2         | 2
3         | 3
4         | 1
4         | 3
5         | 3

从服务员表中,我需要得到每个职位有多少服务员。

期望结果:

艺术:3歌手:2舞者:4

提前谢谢!

我使用以下代码获得了我想要的结果:

$member_ids = Attendance::pluck('member_id');
$positions = Position::whereHas('members', function($query) use($member_ids){
return $query->whereIn('id', $member_ids);
})->get();
$datas = [];
foreach($positions as $position){
$position_id = $position->id;
$subdata = Attendance::whereHas('member.positions', function($query) use($position_id){
return $query->where('id', $position_id);
})->get();
$datas[] = ['position' => $position->position_name, 'count' => $subdata->count()];
}
return view('viewfile', compact('datas'));

在我的刀片文件上:

@foreach($datas as $data)
<td>{{ $data['position'] }}</td>
<td>{{ $data['count'] }}</td>
@endofreach

希望这对将来的某个人有所帮助。

最新更新