CakePHP way to group data by months from SQL
For Example I have tables - Orders1, Orders2, Orders3, Users.
I need to make monthly and quartaly reports for each user. For example I am creating a function in Orders1 model quartal_sum_by_users($users, $quarter)
. then I make something like this:
$cost = 0;
foreach($users as $user) {
while($month <= 3) { // first three months
$orders = $this->Order1->find('all', array(
'recursive' => -1,
'fields' => array('DISTINCT id', 'COALESCE(cost+work_cost+work_installation_cost, 0) AS amount'),
'conditions' => array(
'MONTH(date_ordered)' => $month,
'YEAR(date_ordered)' => $year,
'current_status' => 3
)
));
foreach($orders as $order开发者_如何学JAVA) {
$cost[$month] += $order[0]['amount'];
}
$month++;
} // WHILE
} // FOREACH
So, this is working but very slowly (system from I am migrating this is working on plain PHP and SQL queries and doing fine) and I have 400+ users, and more than 1000 for each Order table.
What is the best way to make it happen in CakePHP style?
The solution should be put as answer, not as comment. Otherwise this question will be marked as unanswered forever.
Anyway... this is what you need to do to group by:
$this->Order1->find('all', array(
'recursive' => -1,
'fields' => 'YOUR_FIELDS',
'conditions' => 'YOUR_CONDITIONS',
'group' => 'THE_FIELD_YOU_WANT_TO_USE_AS_GROUP'
));
The option group accepts an array so you can group by multiple fields.
For more complex queries: book.cakephp.org/view/1030/Complex-Find-Conditions
精彩评论