我有很多关系
Attendees belongsToMany ScheduledPrograms
Attendees belongsToMany ScheduledProgramSegments
我急切地加载与会者(没有清理额外代码的appoligies,我把它留下以防它相关)
控制器内的
$programs = ScheduledProgram::where('registration_start_date', '<=', $today)
->where('end_date', '>=', $today)
->with(['attendees'=>function($q) use ($user_id) {
$q->where('user_id', $user_id);
}])
->with(['scheduledProgramSegments.attendees'=>function($q) use ($user_id) {
$q->where('user_id', $user_id);
}])
->get();
return View::make('admin/users/show',compact('programs');
我如何热切加载与会者的数量?
我使用访问器来查看我的视图中的计数
在模型中
public function getRegisteredCountAttribute()
{
return $this->attendees()->wherePivot('registered',1)->count();
}
查看
<td>{{{$program->registeredCount}}}</td>
@foreach($program->scheduledProgramSegment as $program_seg)
<td>{{{$program_seg->registeredCount}}}</td>
...
但每次都会查询,因此我有大约300个查询......
答案 0 :(得分:1)
$programs = ScheduledProgram::where('registration_start_date', '<=', $today)
->where('end_date', '>=', $today)
->with([
'attendees'=>function($q) use ($user_id) {
$q->where('user_id', $user_id);
},
'scheduledProgramSegments.registeredAttendees'=>function($q) {
$q->wherePivot('registered', true);
},
'scheduledProgramSegments.attendees'=>function($q) use($user_id) {
$q->where('user_id', $user_id);
}
])
->get();
在模型内部(ProgramSegment模型)
public function registeredAttendees()
{
return $this->belongsToMany(Attendees::class);
}
查看
{{ $program_seg->registeredAttendees->count() }}