Phil
Phil

Reputation: 2236

how to eager load count in eager loaded relations

I have many to many relation

Attendees belongsToMany ScheduledPrograms
Attendees belongsToMany ScheduledProgramSegments

I eager load the attendees (appoligies for not cleaning out the extra code, i left it in case it's relevent)

inside the controller

$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');

How do I also eager load the count of the attendees?


Extra information

I use an accessor to get the count in my view like so

inside the model

  public function getRegisteredCountAttribute()
  {
    return $this->attendees()->wherePivot('registered',1)->count();
  }

View

      <td>{{{$program->registeredCount}}}</td>  
      @foreach($program->scheduledProgramSegment as $program_seg)    
          <td>{{{$program_seg->registeredCount}}}</td>      
      ...   

but this does a query each time so i have around 300 queries...

Upvotes: 2

Views: 1867

Answers (1)

Arthur Samarcos
Arthur Samarcos

Reputation: 3299

inside the controller

$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();

inside the model (ProgramSegment model)

  public function registeredAttendees()
  {
    return $this->belongsToMany(Attendees::class);
  }

View

{{ $program_seg->registeredAttendees->count() }}

Upvotes: 1

Related Questions