Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Laravel OrderBy relationship count

I'm trying to get the most popular hackathons which requires ordering by the respective hackathon's partipants->count(). Sorry if that's a little difficult to understand.

I have a database with the following format:

hackathons     id     name     ...  hackathon_user     hackathon_id     user_id  users     id     name 

The Hackathon model is:

class Hackathon extends \Eloquent {     protected $fillable = ['name', 'begins', 'ends', 'description'];      protected $table = 'hackathons';      public function owner()     {         return $this->belongsToMany('User', 'hackathon_owner');     }      public function participants()     {         return $this->belongsToMany('User');     }      public function type()     {         return $this->belongsToMany('Type');     } } 

And HackathonParticipant is defined as:

class HackathonParticipant extends \Eloquent {      protected $fillable = ['hackathon_id', 'user_id'];      protected $table = 'hackathon_user';      public function user()     {         return $this->belongsTo('User', 'user_id');     }      public function hackathon()     {         return $this->belongsTo('Hackathon', 'hackathon_id');     } } 

I've tried Hackathon::orderBy(HackathonParticipant::find($this->id)->count(), 'DESC')->take(5)->get()); but I feel like I made a big mistake (possibly the $this->id), because it doesn't work at all.

How would I go about trying to get the most popular hackathons which is based on the highest number of related hackathonParticipants?

like image 243
Joe Torraca Avatar asked Jun 13 '14 15:06

Joe Torraca


1 Answers

This works for me in Laravel 5.3, using your example:

Hackathon::withCount('participants')->orderBy('participants_count', 'desc')->paginate(10);  

This way it is ordered on the query and the pagination works nicely.

like image 159
kJamesy Avatar answered Sep 19 '22 11:09

kJamesy