<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>

CC BY-SA 4.0
2016-08-01T18:51:15.890Z
2019-04-01T17:19:06.903Z
2019-04-01T17:19:06.903Z
Tim Kelty
<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>

<plugin-development>
Add AVG, SUM to an element field
# 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>


---

