I have a table of videos, a table of users and a pivot table of "favourites" (people who favourited the videos). I want to order the results of the query ranking by the most favourited first.
I will define the relevant fields of the tables and models below.
Videos Table: id, title
Users Table: id
Favourites Table: id, video_id, user_id
Videos Model:
public function favourited()
{
return $this->belongsToMany('User', 'favourites', 'video_id', 'user_id');
}
This is an sql example of what I am trying to do with Eloquent
SELECT
videos.title,
COUNT(favourites.id) AS FavouriteCount
FROM videos
LEFT JOIN favourites ON videos.id = favourites.video_id
GROUP BY videos.id
ORDER BY FavouriteCount desc
For more information see here http://laravel.com/docs/4.2/queries