我有一个模特'图片' (数据库表' uploaded_pictures')有很多'喜欢'(s)
private function likeWrapper() {
return $this->hasMany( 'Like', 'typeId');
}
public function likes() {
return $this->likeWrapper()->where( 'type', '=', Config::get( 'enums.content_types.PICTURE' ) )->get();
}
现在我想创建一个页面,分页,返回按喜欢计数排序的所有图片。我使用Collection sortBy方法完成了这项工作:
$pictures = Picture::get()->sortByDesc( function($picture) {
return $picture->likes()->count();
});
但是这个结果不能分页。我有一个原始查询来完成这项工作,但我很难将其转换为Eloquent查询构建器:
$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));
Eloquent中此查询的等效内容是什么?我使用的是Laravel 4.2.11。
答案 0 :(得分:0)
我希望它会起作用:
$pictures = Picture::leftjoin('likes', 'pictures.id', '=', 'likes.typeId')
->select(DB::raw('pictures.*, COUNT(likes.id) as countLikes'))
->where('likes.type', '=', 'Picture')
->orWhere('likes.typeId')
->orderBy('countLikes', 'DESC')
->groupBy('pictures.id')
->get();