Count the total of a polymorphic pivot relation

Submitted by Mahmoud_Zalt - 6 years ago

That's a nice trick

// I have course and subscriber where subscriber can view a courses and other models, all are viewables.

// the course model relation:

public function voters()
    return $this->morphToMany('Moubarmij\Models\Subscriber', 'votables');

// the subscriber model relation:

public function views()
    return $this->morphedByMany('Moubarmij\Models\Video', 'viewables');

// to get the number of votes of the course:

// add this scope to the course model:

public function scopeWithNumberOfVotes($query)
    return $query->with(['voters' => function($q)
        return $q->select(DB::raw('count(votables_id) as number_of_votes'))->groupBy('votables_id');

 // usage when queuing the course call this scope:

// ...->withNumberOfVotes()...