How to use Mysql agregate functions with CakePHP

Is there a way to use agregate functions with cakephp? like sum () or avg () with find () method.

UPDATE:

I missed a line in a book

array('fields'=>array('Product.type','MIN(Product.price) as price'), 'group' => 'Product.type');

Display the basic structure for this.

thanks for the help

+4
source share
2 answers

In the fields parameter of the find invocation method, you can pass the field processed by the aggregated function. Example:

 $Model->find('all', array( 'anything' => array(/* */), 'fields' => array( 'SUM (Model.attribute) AS total', 'OTHERFUNCTION(OModel.other_attribute) AS other' ), 'otherthing' => array(/* */) ) ); 
+5
source

Similarly, since CakePHP is just a PHP framework.

 <?php // Make a MySQL Connection $query = "SELECT type, SUM(price) FROM products GROUP BY type"; $result = mysql_query($query) or die(mysql_error()); // Print out result while($row = mysql_fetch_array($result)){ echo "Total ". $row['type']. " = $". $row['SUM(price)']; echo "<br />"; } ?> 
-5
source

Source: https://habr.com/ru/post/1347193/


All Articles