简体   繁体   English

cakephp-按年,月分组

[英]cakephp - using group by year, month

I have three tables, branches, children and invoices - children hasmany invoices. 我有三个表,分支机构,子级和发票-子级hasmany发票。 And branches hasmany children 和分支机构有很多孩子

I'm trying to allow a user to query the database to get all the invoices for children which are in a given branch, also the user may have entered a date range. 我试图允许用户查询数据库以获取给定分支中所有子代的发票,而且用户可能已经输入了日期范围。 Either way, I want to select all the invoices and have them grouped so that they are easy to display in a table per month. 无论哪种方式,我都希望选择所有发票并将其分组,以便易于在每个月的表格中显示它们。 ie, user wants all invoices from jan 2013-> jan 2014. Then I display all the invoices but grouped so all jan2013 are together, feb2013 etc... (also, if there was an easy to get the sum total of the invoices for each month somehow that would be cool) 也就是说,用户想要从2013年1月到2014年1月的所有发票。然后显示所有发票,但将它们分组,以便所有jan2013在一起,feb2013等...(此外,如果很容易获得发票的总和,每个月以某种方式会很酷)

At the minute I have: 此刻我有:

$conditions['Child.branch_id'] = $branch_id;
if($from != '') $conditions['Invoice.created >='] = $from;
if($to != '') $conditions['Invoice.created <='] = $to;
$fields = array('Invoice.*', 'Child.*', 'YEAR(Invoice.created) as year', 'MONTH(Invoice.created) as month');
$group = array('YEAR(Invoice.created)', 'MONTH(Invoice.created)');
$order = array('Invoice.created');
$kidsInvoices = $this->Invoice->find('all', array(  'conditions'=>$conditions,
                                            'fields'=>$fields,
                                            'group'=>$group,
                                            'order'=>$order));

But it returns only 2 records, when it should return all which would be 5. I noticed that of my 5 invoices they span only 2 months, so I'm guessing my incorrect code is just getting one invoice per month. 但是它只返回2条记录,而应该返回所有5条记录。我注意到我的5张发票中只有2个月,所以我猜我的错误代码每月仅获得一张发票。

Can anyone tell me how I can get the results I want? 谁能告诉我如何获得想要的结果?

If I understand what you want to do correctly, you're looking for order, not group. 如果我了解您要正确执行的操作,则是在寻找订单,而不是分组。 Group by will make all the rows with have the same results for each of the given columns compress down to one row, resulting in the fewer rows you're seeing in your results. 分组依据将使所有给定列具有相同结果的所有行压缩为一行,从而使结果中看到的行减少。

 $order = array('year', 'month');
 $kidsInvoices = $this->Invoice->find('all', array(  'conditions'=>$conditions,
                                        'fields'=>$fields,
                                        'order'=>$order));

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM