2017-06-15 39 views
0

所以我有一個部分,人們可以發表評論,並給予這些意見。 我想基於有多少喜歡來組織評論。由關係計數laravel 4.2訂購查詢

所以我用這樣的

$art = Article::with('category') 
->with(array('comments' => function($comments){ 
    //i get the comments related to the article and the count of likes it has 
    $comments->with('likesCount'); 
})) 
->find($id); 

這是模型

<?php 

class Comment extends Eloquent { 
    public function likes() 
    { 
     return $this->hasMany('CommentsLike','comment_id'); 
    } 
    //here i take the count of likes, if i use ->count() it throw 
    public function likesCount() 
    { 
     return $this->likes() 
     ->groupBy('comment_id') 
     ->selectRaw('comment_id,count(*) as comment_likes'); 
    } 
} 

我怎麼能基於排序我的評論我在likesCount

回答

0

使用ORDERBY有()likesCount()函數。

public function likesCount() 
{ 
    return $this->likes() 
    ->groupBy('comment_id') 
    ->selectRaw('comment_id,count(*) as comment_likes') 
    ->orderBy('comment_likes', 'desc'); 
}