在Laravel ORM中通过投票排序

时间:2014-06-25 20:43:44

标签: php laravel sum eloquent

我有3个模特......分类,发布,投票

查看某个类别时,我会显示该类别中所有帖子的索引。所以我在我的观点中做了foreach ($category->posts as $post)这样的事情。

我现在的问题是如何根据他们的投票总数来订购帖子?

我有标准关系设置,因此帖子有多个投票。

1 个答案:

答案 0 :(得分:1)

您可以通过在Post模型上定义帮助关系并在加载关系 OR 之后对集合进行排序,只需加入投票并在查询中进行排序即可。< / p>

1关系

// Post model
public function votesSum()
{
  return $this->hasOne('Vote')->selectRaw('post_id, sum(votes) as aggregate')->groupBy('post_id');
}

// then
$category->posts->load('votesSum'); // load relation on the collection

$category->posts->sortByDesc(function ($post) {
    return $post->votesSum->aggregate;
});

// access votes sum like this:
$category->posts->first()->votesSum->aggregate;

2加入

$category->load(['posts' => function ($q) {
   $q->leftJoin('votes', 'votes.post_id', '=', 'posts.id')
       ->selectRaw('posts.*, sum(votes.votes) as votesSum')
       ->groupBy('posts.id')
       ->orderBy('votesSum', 'desc');
}]);

// then access votes sum:
$category->posts->first()->votesSum;

您可以使用范围:

// Post model
public function scopeOrderByVotes($query)
{
    $query->leftJoin('comments','comments.post_id','=','posts.id')
      ->selectRaw('posts.*,sum(comments.id) as commentsSum')
      ->groupBy('posts.id')
      ->orderBy('commentsSum','desc');
}

// then
$category = Category::with(['posts' => function ($q) {
    $q->orderByVotes();
}])->whereSlug($slug)->firstOrFail();