2013-01-09 45 views
0

我使用中可容納的行爲和我發現的結果(「全部」)來過濾結果是:使用中可容納的行爲在CakePHP 2.2.4

array(
    (int) 0 => array(
     'User' => array(
      'id' => '106', 
      'email' => '[email protected]', 
      'pwd' => '0433c024cb08be13000d59a347e640482843f46f177e95749dc6599c259617fd3491dcb940b47693cbbc7f65a2cc5ef62deca2e600c1be133ad54170f7d1fbd1', 
      'role_id' => '3', 
      'active' => '1' 
     ), 
     'Lead' => array(
      'id' => '6' 
     ), 
     'Estimate' => array(
      (int) 0 => array(
       'lead_id' => '6', 
       'Estimate' => array(
        (int) 0 => array(
         'TOT_count' => '2' 
        ) 
       ) 
      ) 
     ) 
    ) 
) 

我要統計有多少估計也有處於領先。

總數(2)是正確的,但我看到嵌套的「估計」數組,爲什麼?

結果我想獲得的是:

array(
    (int) 0 => array(
     'User' => array(
      'id' => '106', 
      'email' => '[email protected]', 
      'pwd' => '0433c024cb08be13000d59a347e640482843f46f177e95749dc6599c259617fd3491dcb940b47693cbbc7f65a2cc5ef62deca2e600c1be133ad54170f7d1fbd1', 
      'role_id' => '3', 
      'active' => '1' 
     ), 
     'Lead' => array(
      'id' => '6' 
     ), 
     'Estimate' => array(
      'TOT_count' => '2' 
     ) 
    ) 
) 

這是發現:

$options = array(
        'contain' => array(
         'User', 
         'Estimate' => array(
          'fields' => 'COUNT(*) AS TOT_count'        
         ) 
        ), 
        'conditions' => array('Lead.id' => 6), 
        'fields' => 'User.*',       
        'limit' => 1 

       ); 

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

我該怎麼辦呢? 謝謝!

回答

3

當您使用「自定義」AS語句時,在您的案例TOT_count中,Cake將始終將其放在名爲0的結果鍵中。您可以通過在模型中將TOT_count定義爲virtualField來避免此問題。這樣它將直接嵌套在結果集中的模型名稱下。

其次,lead_id被強制檢索,因爲它是「需要」與Lead模型進行連接。如果沒有那些信息,它將無法正確檢索所有數據。

+0

很好的解釋!謝謝 – Dail

+1

只要您在查找中使用「AS」,它就不會執行此操作。當你沒有正確使用它時會這樣做。 [virtualFields](http://book.cakephp.org/2.0/en/models/virtual-fields.html)存在原因 – dogmatic69

+0

@ dogmatic69 D'oh,當然!我以前用過它們,所以我應該記住。感謝您指出這一點,我已經更新了答案,以更好地反映正確的方式來做到這一點。 – Oldskool