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.


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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.