I have Comments here wherein user can rate a content.
I want to get the average rating per content, how do I efficiently get the average?
I have the following code to get the Average:
$cids = Drupal::entityQuery('comment') ->condition('entity_id', $variables['row']->nid) ->condition('entity_type', 'node') ->condition('comment_type', 'content_rating') ->execute(); $comments = []; $totalRating = 0; if ($cids) { foreach ($cids as $cid) { $comment = Comment::load($cid); $comments[] = $comment->get('field_rating')->value; } $totRating = array_sum($comments) / count( $comments ); $totalRating = ceil($totRating); }
I know this is not efficient because I’m getting ALL the comments and manually computing for the average rating.
How can I get the average rating on a query level?