用户可以提供的帖子评分,如何按其平均评分搜索帖子。
发布模型
//post model
public function avgRating()
{
return $this->ratings()->selectRaw('avg(ratings) as avgRatings,post_id')->groupBy('post_id');
}
public function getAvgRatingAttribute()
{
if ( ! array_key_exists('avgRating', $this->relations)) {
$this->load('avgRating');
}
$relation = $this->getRelation('avgRating')->first();
return ($relation) ? $relation->avgRatings : null;
}
上面的代码我可以获得每个帖子的平均评分,现在我如何按评分来过滤帖子,例如获得平均评分为1或平均评分为2或平均评分为3或平均评分为4或平均评分为5的帖子,
//To filter data
public function filter()
{
$post= (new Post)->newQuery();
if ($request->has('averageRatings')) {
$post->whereHas('avgRating', function ($query) use ($request) {
$query->where('rating', $request->input('averageRatings'))->avgRating;
});
}
$results = $institute->get();
}