I have a Model 'Picture' (database table 'uploaded_pictures') that has many 'Like'(s)
private function likeWrapper() {
return $this->hasMany( 'Like', 'typeId');
}
public function likes() {
return $this->likeWrapper()->where( 'type', '=', Config::get( 'enums.content_types.PICTURE' ) )->get();
}
Now I want to create a page, paginated, that returns all Pictures ordered by the count of likes. I made this work using the Collection sortBy method:
$pictures = Picture::get()->sortByDesc( function($picture) {
return $picture->likes()->count();
});
But this result can't be paginated. I have a raw query that does the job, but I struggle translate it to Eloquent query builder:
$query = "SELECT p.*, COUNT(l.id) AS countLikes
FROM uploaded_pictures AS p
LEFT OUTER JOIN
(SELECT id, typeId, type FROM likes WHERE type='picture') AS l
ON p.id = l.typeId
WHERE date<='$referenceDate'
GROUP BY p.id, l.typeId
ORDER BY countLikes DESC";
$pictures = DB::select(DB::raw($query));
What is the equivalent of this query in Eloquent? I'm using Laravel 4.2.11.