![](/img/trans.png)
[英]Using Containable behavior to filter results in Cakephp 2.2.4
[英]How to count the result using find() in CakePHP 2.2.4?
我正在使用Cakephp 2.2.4 ,我需要檢索屬於該用戶的Lead列表( 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'
)
)
)
)
看起來不錯,但我需要計算估算值(估算數組),我想獲取估算值的數量,而不是檢索包含所有字段(估算表)的數組。
我該怎么做?
我需要 :
如圖所示的引線陣列
如圖所示的用戶數組
如圖所示的服務陣列
估計 (在這種情況下,僅估計總數... 1
)
查找非常簡單:
$options = array('conditions' => array('User.id' => 106));
debug($this->Lead->find('all', $options));
嘗試這樣的事情,不是100%地確定它會工作,但是如果沒有的話,還是值得一試。我建議您拖曳Cakephp文檔來檢索您的數據:
$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
$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
方法執行它。 在不了解表模式和模型關系的細節的情況下,很難給出關於如何構造查詢的細節,但是通過查看表規范並為具有給定id的每個Estimate
提取一個sql COUNT
語句,這應該不會太困難。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.