如何使用CakePHP 2.2.4中的find()计算结果?

时间:2013-01-09 17:52:10

标签: php cakephp cakephp-2.0

我正在使用 Cakephp 2.2.4 ,我需要检索属于该用户的潜在客户列表( id = 106 )。

查询结果为:

array(
    (int) 0 => array(
        'Lead' => array(
            'id' => '6',
            'user_id' => '106',
            'date' => '2012-12-31 22:15:23',
            'ip' => '127.0.0.1',
            'service_id' => '1',
            'location' => 'Rome',
            'message' => 'Message Message',
            'telephone' => null,
            'active' => null
        ),
        'User' => array(
            'id' => '106',
            'email' => 'daje@daje.it',
            'pwd' => '0433c024cb08be13000d59a347e640482843f46f177e95749dc6599c259617fd3491dcb940b47693cbbc7f65a2cc5ef62deca2e600c1be133ad54170f7d1fbd1',
            'role_id' => '3',
            'active' => '1'
        ),
        'Service' => array(
            'id' => '1',
            'name' => 'Primo servizio'
        ),
        'Estimate' => array(
            (int) 0 => array(
                'id' => '1',
                'lead_id' => '6',
                'user_id' => '106'
            )
        )
    )
)

它看起来不错,但我需要计算Estimates(Estimate数组),我想要检索估计数,而不是包含所有字段(估计表)的数组。

我该怎么做?

我需要:

显示

Lead 数组

显示

用户数组

显示

服务数组

估算(仅限估算总数...在这种情况下为1

发现非常简单:

$options = array('conditions' => array('User.id' => 106));

debug($this->Lead->find('all', $options));

2 个答案:

答案 0 :(得分:3)

尝试这样的事情,不是百分之百确定它会起作用但是值得一去,如果不是我建议搜索cakephp文档来检索你的数据:

$options = array(
    'fields' => array('Lead.*', 'User.*', 'Service.*', 'count(Estimate.id)'),
    'conditions' => array('User.id' => 106)
);

答案 1 :(得分:0)

如果没有深入了解Cake ORM的内部,假设您不需要在查询时立即执行此操作,那么您是否只能在获取后以编程方式获取估计数组的count

http://php.net/manual/en/function.count.php

$leads = $this->Lead->find('all',$options);
foreach($leads as $lead){
  //get the number of estimates for every lead result
  $lead_num = count($lead['Estimate']);
}

或者,您可以手动为此一次提取编写连接查询,并使用Cake Model类的query方法执行它。在不知道表模式和模型关系的细节的情况下,很难给出关于如何构造查询的细节,但是通过查看表规范并为每个语句提取sql COUNT语句,这应该不会太困难。具有给定ID的Estimate