2013-08-03 84 views
1

是否可以使用CakePHp分頁下面的查詢?Cakephp分條與條款

select u.email,(select count(*) from relatives as iu where iu.user_id=u.id) as iu_count,(select count(*) from friends as ff where ff.user_id=u.id) as ff_count from users as u having (iu_count>0 OR ff_count>0) 

我試圖做到這一點使用CakePHP分頁,但它給出了一個錯誤的「iu_count」和「ff_count」不在查詢選擇部分可用,但他們在HAVING子句可用。我的cakephp分頁查詢如下。

SELECT COUNT(*) AS `count` FROM `abc`.`users` AS `User` WHERE 1 GROUP BY `User`.`id` having (iu_count>0 OR ff_count>0) 

需要幫助/指導才能使用它。

回答

1

今天我GOOGLE了更多,找到一個解決方案,適合我。解決方案是重寫模型中的paginateCount方法。

下面是一個被覆蓋的功能。

public function paginateCount($conditions = null, $recursive = 0, $extra = array()) { 
     $parameters = compact('conditions', 'recursive'); 

     if (isset($extra['group'])) { 
      $parameters['fields'] = array("iu_count","ff_count"); 
      //$parameters['fields'] = $extra['group']; 
      if (is_string($parameters['fields'])) { 
       // pagination with single GROUP BY field 
       if (substr($parameters['fields'], 0, 9) != 'DISTINCT ') { 
        $parameters['fields'] = 'DISTINCT ' . $parameters['fields']; 
       } 
       unset($extra['group']); 
       $count = $this->find('count', array_merge($parameters, $extra)); 
      } else { 
       // resort to inefficient method for multiple GROUP BY fields 
       $count = $this->find('count', array_merge($parameters, $extra)); 
       $count = $this->getAffectedRows(); 
      } 
     } else { 
      // regular pagination 
      $count = $this->find('count', array_merge($parameters, $extra)); 
     } 
     return $count; 
    } 

這裏的 「陣列(」 iu_count 「 」ff_count「);」是我在HAVING子句中使用的虛擬字段。如果在HAVING子句中沒有需要的虛擬字段,則將$ extra ['group']分配給$ parameter ['fields']。

希望這個解決方案能幫助某個人。