按关系计数laravel 4.2进行订单查询

时间:2017-06-15 20:21:48

标签: php laravel relationships

所以我得到了一个部分,人们可以发表评论并给予这些评论。 我想根据它有多少喜欢来组织评论。

所以我使用这样的东西

$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

中的内容对评论进行排序

1 个答案:

答案 0 :(得分:0)

orderBy()用于likesCount()功能。

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