course when you register on learnphalcon
The examples on this site are currently tested to work on Phalcon V3.4 and Phalcon Devtools V3.2 Some issues may arise when using later versions.

Please get in touch or post a comment below the post if you encounter a problem.

Phalcon provides a range of functionality for working with Model classes which provides an independence from the persistence layer of the application. This layer of abstraction away from the database itself further decouples the application from the database thereby future proofing the system. In providing this layer of functionality Phalcon needs to provide as much of the functionality as possible as would normally be provided by a language like SQL.

SQL aggregate functions allows for users to simply perform calculations across a range of data.

This functionality is described in the phalcon documentation here https://docs.phalconphp.com/en/latest/db-models#generating-calculations

Using this functionality we can add a getAverageRating() function to the Court.php model class. Modify the file /app/models/Court.php and add the following function.

public function getAverageRating()
	$id = $this->id;
	$averageRating = CourtRating::average(['conditions' => "courtid = $id",'column' => 'rating']);
	return $averageRating;

It is now easy to display the average rating for each court on the view app/views/court/search.phtml.

Add the following code snippet at the top of the view to pull in the "rating" asset collection.


Next, modify the /app/views/court/search.phtml file and add three extra column headers as follows:

Now add the following line to the table body which include an extra column in the table for the average court rating.

<td><?php echo $court->getAverageRating()?></td>
	<input id="fieldRating" name="rating" 
				value="<?php echo $court->getAverageRating()?>" 
				type="text" class="rating rating-loading" data-min=0
				data-max=5 data-step=1 data-size="sm" data-display-only="true">

Finally add an extra column at the end of the table which will contain a link allowing users to provide an additional rating for any of the courts listed. This will tie the court search page back to the /app/courtRating/new.phtml view created in step 1 and will provide a natural menu-driven way to access this functionality. This column is inserted between the Edit and Delete links as follows:

The search page will now include a column for the average star rating for each court and for the average as a decimal as below:

In the next post, I'll explain how to make it possible for the user to "drill down" and see the detail behind each rating.