@@ -378,36 +378,32 @@ public function deleteReview(int $reviewId): bool
378378 */
379379 public function ratingCounts (?string $ department = null , bool $ approved = true ): array
380380 {
381- $ min = config ('review-rateable.min_rating_value ' , 1 );
382- $ max = config ('review-rateable.max_rating_value ' , 5 );
381+ $ min = config ('review-rateable.min_rating_value ' , 1 );
382+ $ max = config ('review-rateable.max_rating_value ' , 5 );
383+ $ reviewTable = (new Review )->getTable ();
384+ $ ratingTable = (new Rating )->getTable ();
383385
384- $ reviewQuery = $ this ->reviews ()
385- ->where ('approved ' , $ approved );
386+ $ query = Rating::select ("{$ ratingTable }.value " , DB ::raw ('COUNT(*) as total ' ))
387+ ->join ($ reviewTable , "{$ ratingTable }.review_id " , '= ' , "{$ reviewTable }.id " )
388+ ->where ("{$ reviewTable }.reviewable_type " , $ this ->getMorphClass ())
389+ ->where ("{$ reviewTable }.reviewable_id " , $ this ->getKey ())
390+ ->where ("{$ reviewTable }.approved " , $ approved );
386391
387392 if ($ department ) {
388- $ reviewQuery ->where (' department ' , $ department );
393+ $ query ->where ("{ $ reviewTable } . department" , $ department );
389394 }
390395
391- $ rawCounts = Rating::select ('value ' , DB ::raw ('count(*) as count ' ))
392- ->whereHas ('review ' , function ($ q ) use ($ reviewQuery ) {
393- $ sql = $ reviewQuery ->toBase ()->toSql ();
394- $ bindings = $ reviewQuery ->toBase ()->getBindings ();
395- $ q ->from (DB ::raw ("( {$ sql }) as reviews_sub " ))
396- ->whereColumn ('reviews_sub.id ' , 'ratings.review_id ' );
397- foreach ($ bindings as $ i => $ b ) {
398- $ q ->addBinding ($ b , 'where ' );
399- }
400- })
401- ->groupBy ('value ' )
402- ->pluck ('count ' , 'value ' )
396+ $ raw = $ query
397+ ->groupBy ("{$ ratingTable }.value " )
398+ ->pluck ('total ' , 'value ' )
403399 ->all ();
404400
401+ // zero-fill any missing star values
405402 $ counts = [];
406403 for ($ i = $ min ; $ i <= $ max ; $ i ++) {
407- $ counts [$ i ] = $ rawCounts [$ i ] ?? 0 ;
404+ $ counts [$ i ] = $ raw [$ i ] ?? 0 ;
408405 }
409406
410407 return $ counts ;
411408 }
412-
413409}
0 commit comments