How to use agregate Mysql functions with CakePHP
There is a w开发者_如何学Pythonay to use agregate functions with cakephp? like sum() or avg() with find() method.
UPDATE:
I missed a line in the book
array('fields'=>array('Product.type','MIN(Product.price) as price'), 'group' => 'Product.type');
Showing the basic structure for doing that.
Thanks for the help
In the fields parameter of a find method call, you may pass the field processed by an aggregated function. Example:
$Model->find('all',
array(
'anything' => array(/* */),
'fields' => array(
'SUM (Model.attribute) AS total',
'OTHERFUNCTION(OModel.other_attribute) AS other'
),
'otherthing' => array(/* */)
)
);
In exactly the same way, 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 />";
}
?>
精彩评论