关于php:如何在CakePHP 2.2.4中使用find()计算结果?

How to count the result using find() in CakePHP 2.2.4?

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

查询的结果是:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
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' => '[email protected]',
            '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'
            )
        )
    )
)

它看起来不错,但我需要计算估算值(估算数组),我想获取估算值的数目,而不是包含所有字段(估算表的字段)的数组。

我该怎么办?

我需要:

所示的引线数组

显示的用户数组

显示的服务数组

估计(仅估计总数...在这种情况下为1)

发现非常简单:

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

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

尝试类似的方法,不是100%地确定它会工作,但是如果没有的话,还是值得一试。我建议拖网cakephp文档来检索您的数据:

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


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

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

1
2
3
4
5
$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方法执行该查询。在不了解表模式和模型关系的细节的情况下,很难给出关于如何构造查询的细节,但是通过查看表规范并为每个count语句,这应该不会太困难>具有给定ID。