Answers.Body: <p>In this case, since I happen to be dealing with reviews, The Star Reviews plugin calculates averages when new ratings are posted: <a href="https://www.doublesecretagency.com/plugins/star-ratings" rel="nofollow noreferrer">https://www.doublesecretagency.com/plugins/star-ratings</a></p>
  
Answers.ContentLicense: CC BY-SA 4.0
Answers.CreationDate: 2016-08-01T18:51:15.890Z
Answers.LastActivityDate: 2019-04-01T17:19:06.903Z
Answers.LastEditDate: 2019-04-01T17:19:06.903Z
Answers.UserDisplayName: Tim Kelty
Body: <p>I want to use AVG/SUM mysql and add it to the results of a criteria.
  Trying to strategize the best way to achieve this.</p>
  
  <p>I'm looking at <code>elements.onBuildElementsQuery</code>, where it seems I could do something like...<code>$query-&gt;addSelect('AVG(field_reviewRating) as reviewRatingAverage');</code></p>
  
  <p>Or do I need to make this a field type (read only)?</p>
  
  <p>I'm going to be dealing with several thousands of entries, so I don't want to have to query everything and loop through.</p>
  
  <p>I could also just call a service from Twig e.g. (<code>craft.custom.getReviewStats(entryModel)</code>), but I wanted to avoid having to add another query for each returned element.</p>
  
Tags: <plugin-development>
Title: Add AVG, SUM to an element field
ThreadText: # Add AVG, SUM to an element field
  
  (Asked by: username_0 on 2016-08-01)
  
  I want to use AVG/SUM mysql and add it to the results of a criteria.
  Trying to strategize the best way to achieve this.
  
  I'm looking at `elements.onBuildElementsQuery`, where it seems I could do something like...`$query->addSelect('AVG(field_reviewRating) as reviewRatingAverage');`
  
  Or do I need to make this a field type (read only)?
  
  I'm going to be dealing with several thousands of entries, so I don't want to have to query everything and loop through.
  
  I could also just call a service from Twig e.g. (`craft.custom.getReviewStats(entryModel)`), but I wanted to avoid having to add another query for each returned element.
  
  **Tags:** plugin-development
  
  
  ---
  
  ## 1 answers
  
  ### Answer by username_0 on 2016-08-01. Score: 2
  
  In this case, since I happen to be dealing with reviews, The Star Reviews plugin calculates averages when new ratings are posted: <https://www.doublesecretagency.com/plugins/star-ratings>
  
  
  ---
  
  