Skip to content

Commit 85b864d

Browse files
committed
Working on listing models with average ratings
1 parent 4cfb5cd commit 85b864d

File tree

3 files changed

+27
-0
lines changed

3 files changed

+27
-0
lines changed

src/Contracts/ReviewRateable.php

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -148,6 +148,8 @@ public function getRecentRatings($id, $limit = 5, $sort = 'desc');
148148
*/
149149
public function getRecentUserRatings($id, $limit = 5, $approved = true, $sort = 'desc');
150150

151+
public function getCollectionByAverageRating($rating);
152+
151153
/**
152154
*
153155
* @param $id

src/Models/Rating.php

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -150,6 +150,26 @@ public function getRecentUserRatings($id, $limit = 5, $approved = true, $sort =
150150
return $rating;
151151
}
152152

153+
public function getCollectionByAverageRating($rating)
154+
{
155+
$ratings = $this->selectRaw('reviewrateable_id as modelId, AVG(rating) as avgRating')
156+
->with($this->reviewrateable())
157+
->groupBy('modelId')
158+
->havingRaw('AVG(rating) >= '.$rating)
159+
->get();
160+
161+
$ratings = $ratings->mapToGroups(function ($item, $key) {
162+
return [$item['name'] => $item['reviewrateable']];
163+
});
164+
165+
// Do something to separate the featurable models in each subsection by model type
166+
foreach($ratings as $i => $rows) {
167+
$ratings[$i] = $rows->groupBy('reviewrateable_type');
168+
}
169+
170+
return $ratings;
171+
}
172+
153173
/**
154174
* @param $id
155175
*

src/Traits/ReviewRateable.php

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -262,6 +262,11 @@ public function getRecentUserRatings($id, $limit = 5, $approved = true, $sort =
262262
return (new Rating())->getRecentUserRatings($id, $limit, $approved, $sort);
263263
}
264264

265+
public function getCollectionByAverageRating($rating)
266+
{
267+
return (new Rating())->getCollectionByAverageRating($rating);
268+
}
269+
265270
/**
266271
* @param $id
267272
*

0 commit comments

Comments
 (0)