Jump to content

Selectors and aggregation functions


theoretic
 Share

Recommended Posts

Hi there! And thanks for Processwire!

This is rather a question than a feature request, maybe there's a well known solution which i missed.

So what about aggregation in selectors? Let's suppose we have a PW-powered shop where any product has a rating made by customers. Every time the user polls two data fields are updated: points and votes. The rating is calculated as this:

$rating = $page->points / $page->votes;

It was easy, yeah. But what about sorting products by their rating? Basically there are two ways of doing it:

  1. Creating one more field called rating and updating it after every vote. For sure it will work, but we have to create an extra data field which in fact stores data based on two another fields. Bad practice i think.
  2. Getting all products into array and applying a cutom sort function. Will work again, but this demands much more coding than using the native PW selectors.

But how could it be done in the best possible way? Let's imagine this:

$products = $page->children("sort=points/votes");

Or maybe this:

function rating($a,$b){
	return $a->points/$a->votes > $b->points/$b->votes;
	}

$products = $page->children("sort=rating()");

Okay, let's go even deeper. Maybe we need "virtual" fields which are not stored in DB tables like other PW fields but represent the dynamically calculated values?

$page->rating = function(){
	return $page->points/$page->votes;
	}

$products = $page->children("sort=rating");

Will be glad to see advice on the best practices. Thanks in advance!

Link to comment
Share on other sites

On 2/14/2018 at 6:42 AM, theoretic said:

Okay, let's go even deeper. Maybe we need "virtual" fields which are not stored in DB tables like other PW fields but represent the dynamically calculated values?

for the most part, the hidden field option i think is best, but does take some logic and page saving; If you do want to have them be virtual, then you can do a hook

wire()->addHookProperty('Page(template=product)::rating', function($event) {
    $product = $event->object;
	$event->return = $product->points / $product->votes;
});

but you will be limited to in-memory selection, since the property is not in the database

  • Like 4
  • Thanks 1
Link to comment
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
 Share

×
×
  • Create New...