2011-12-07 68 views
1

我有一個翻譯行爲附帶兩個字段的模型:標題和說明。 我在可翻譯字段中添加了一些條件。 像往常一樣分頁,CakePHP首先進行計數,然後提取所有記錄。 當獲取查詢的總記錄:CakePHP翻譯行爲和分頁計數

SELECT COUNT(DISTINCT(`product`.`id`)) AS COUNT 
FROM `products` AS `product` 
    INNER JOIN `i18n` AS `i18nmodel` 
    ON (`product`.`id` = `i18nmodel`.`foreign_key` 
      AND `i18nmodel`.`model` = 'Product' 
      AND `i18nmodel`.`locale` = 'eng') 
    LEFT JOIN `categories` AS `category` 
    ON (`product`.`category_id` = `category`.`id`) 
    LEFT JOIN `vats` AS `vat` 
    ON (`product`.`vat_id` = `vat`.`id`) 
    LEFT JOIN `availables` AS `available` 
    ON (`product`.`available_id` = `available`.`id`) 
WHERE ((`i18n__description`.`content` LIKE '%test%') 
     OR (`i18n__title`.`content` LIKE '%test%') 
     OR (`product`.`code` LIKE '%test%')) 

我得到:

1054: Unknown column 'I18n__description.content' in 'where clause' 

,因爲國際化表未加入爲i18n_ 標題或國際化 _description但i18nmodel

然而,當分頁嘗試檢索查詢的行(不是總記錄)時,一切正常。有沒有解決這個問題的方法?

控制器代碼是這樣的:

$condition = array(); 
foreach ($search as $word) { 
if (strlen($word) > 0) 
$condition[] = array('OR' => array('I18n__description.content LIKE' => '%' . $word . '%','I18n__title.content LIKE' => '%' . $word . '%', 
         'Product.code LIKE' => '%' . $word . '%')); 
} 

$conditions = array('AND' => $condition); 
$products = $this->paginate($conditions); 
+0

你可以發佈你的控制器代碼嗎? –

+0

我添加了條件的部分。 – mentalic

回答

2

這種情況可以簡單地通過創建要分頁模型定製paginateCount方法進行處理。

function paginateCount($conditions = array(), $recursive = null, $extra = array()) { 
    return count($this->find('all', array('conditions' => $conditions))) 
} 
1

paginator計數器不使用翻譯連接,因此您必須在查找之前手動加入。 FindAll不是很好的解決方案,因爲它運行相關的查詢,並且消耗服務器資源。

https://github.com/cakephp/cakephp/issues/1753

解決方案。它不適用於SmoothTranslate行爲,但對上面的代碼稍作修改,它可能是行得通的。 覆蓋之前查找。

function beforeFind($queryData){ 
    if(!empty($this->actsAs['SmoothTranslate']['fields'])){ 
     foreach($this->actsAs['SmoothTranslate']['fields'] as $trkey=>$trval){ 
      if(!is_string($trkey)) $trkey=$trval; 

      $joinFound=false; 
      foreach($queryData['joins'] as $join){ 
      if($join['alias']=='I18n__'.$trkey){ 
       $joinFound=true; break; 
      } 
      } 
      if(!$joinFound){ 
      $newJoin = array(
       'type'=>'LEFT', 
       'table'=>'i18n', 
       'alias'=>'I18n__'.$trkey, 
       'conditions'=>array(
       $this->alias.'.id'=>Set::map(array(
        'type'=>'identifier', 
        'value'=>'I18n__'.$trkey.'.foreign_key', 
       )), 
       'I18n__'.$trkey.'.model'=>$this->alias, 
       'I18n__'.$trkey.'.locale'=>$this->locale, 
       'I18n__'.$trkey.'.field'=>$trkey, 
      ), 
      ); 
      array_push($queryData['joins'], $newJoin); 
      } 
     } 

    } 
    return $queryData; 
    } 
} 
+0

謝謝你的回答,但請閱讀http://stackoverflow.com/questions/how-to-answer,特別是「爲鏈接提供上下文」部分。 –

+0

好的!我在這裏新手:) – lamasgergo