[英]Order articles by average article rating
I want to be able to order my articles based on their rating which I solved using the following query:我希望能够根据我使用以下查询解决的评分来订购我的文章:
return Article::where('private', 0)
->whereIn('movie_id', $movie)
->with(['user', 'movie', 'ratings'])
->withCount(['ratings as average' => function ($query) {
$query->select(\DB::raw('coalesce(avg(value), 0)'));
}])
->orderByDesc('average')
->paginate(10);
The problem is however if an article only has 1 or 2 ratings/votes and they are all positive ratings then the article will rank with other top articles that have many more ratings/votes which gives inaccurate results.然而,问题是如果一篇文章只有 1 或 2 个评分/投票并且它们都是正面评分,那么该文章将与其他具有更多评分/投票的顶级文章一起排名,这会给出不准确的结果。 How would I limit it only to articles with let's say more than 5 votes?我如何将其限制为仅获得超过 5 票的文章? Is there any other other better solution?还有其他更好的解决方案吗?
If ratings
is a relation hasMany, you can simply use:如果ratings
是一个关系 hasMany,您可以简单地使用:
return Article::where('private', 0)
->has('ratings', '>=', 5)
...
To only get articles with 5 or more ratings.仅获取评分为 5 或更多的文章。
You can grab all articles too in your query, with number of ratings:您也可以在查询中获取所有文章,包括评分数:
return Article::where('private', 0)
->withCount('ratings')
...
And you can use a simple condition in your loop to show ratings only for Articles with 5 or more ratings:您可以在循环中使用一个简单的条件来仅显示具有 5 个或更多评分的文章的评分:
@foreach ($articles as $article)
@if ($article->count_ratings >= 5)
// show rating
@endif
@endforeach
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.