在Laravel ORM中按投票排序


Order by Votes in Laravel ORM

我有3个模型…分类,发布,投票

当查看一个类别时,我显示的是该类别中所有帖子的索引。我在视图中设置foreach ($category->posts as $post)

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

我有标准的关系设置,所以一个帖子有很多投票。

您可以在Post模型上定义一个helper关系并在加载关系后对集合进行排序仅通过在查询中加入投票和排序来实现。

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;

你可以使用scope:

// 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();