I have multiple hasMany relations where I want the row count only for the last table.
Users can register for workshops at a specific date and time, so the relations look like 'Workshop' -> hasMany 'Date' -> hasMany 'TimeSlot' -> hasMany 'Registration'.
//Workshop Model
public function workshop_dates(){
return $this->hasMany(WorkshopDate::class);
}
//Date Model
public function workshops(){
return $this->belongsTo(Workshop::class);
}
public function workshop_times(){
return $this->hasMany(WorkshopTime::class);
}
//Time Model
public function workshop_dates(){
return $this->belongsTo(WorkshopDate::class);
}
public function registrations(){
return $this->hasMany(Registration::class);
}
//Registration Model
public function workshop_times(){
return $this->belongsTo(WorkshopTime::class, 'workshop_time_id','id');
}
In my controller I fetch all workshops with all related dates and timelots, but I don't want the user to download all the registration data. I only want them to download the number of registrations for each timeslot. I tried with the 'withCount' function:
return Workshop::with('workshop_dates.workshop_times.registrations')->withCount('registrations')
But this gave me the error 'Call to undefined method App\Workshop::registrations()'
So I created this method in Workshop.php, with the extended version of hasManyThrough:
public function registrations(){
return $this->hasManyDeep(Registration::class, [WorkshopDate::class,WorkshopTime::class]);
}
However, now I get the total number of registrations per workshop in stead of per timeslot.
I'm a laravel beginner and searching for a solution for many hours. All help is appreciated!