2014-10-30 47 views
0

對於CakePhp 2.5對模型功能分頁結果

我在我的控制器中有以下搜索功能。

public function search($query = null, $lim = null) 
{ 
    $tokens = explode(" ", $query); 
     $this->Paginator->settings = array(
        'conditions' => array(
         'Customer.site_id LIKE' => '%' . $this->viewVars['shopId'], 
         'CONCAT(Customer.first_name," ",Customer.last_name," ",Customer.organisation) LIKE' => '%' . implode(' ', $tokens) . '%' 
        ), 
        'limit' => $lim 
       ); 
     $this->set('customers', $this->Paginator->paginate()); 
} 

這工作正常,並得到我想要的結果。

然而,它已經向我建議,我應該把這些搜索功能在我的模型。我可以很容易地做到這一點,並已經這樣做了類似在我的模型如下:

public function getActiveTasks($id){ 
     return $this->Task->find('all', array(
      'conditions' => array(
       'Task.customer_id' => $id, 
       'Task.status' => 0 
      ), 
      'order' => array('Task.due_date ASC'), 
      'recursive' => -1, 
     )); 
    } 

我遇到的問題是,我不能(或不知道如何)使用分頁程序自定義搜索。有沒有辦法對自定義函數的結果進行分頁?

即我可以做到以下幾點:

public function CustomModelSearch($query = null, $lim = null) 
{ 
    return $this->Task->find('all', array(
     'conditions' => array(
      'Customer.site_id LIKE' => '%' . $this->viewVars['shopId'], 
      'CONCAT(Customer.first_name," ",Customer.last_name," ",Customer.organisation) LIKE' => '%' . implode(' ', $tokens) . '%' 
     ), 
     'limit' => $lim 
    )); 
} 

,然後在控制器調用

$results = $this->Model->CustomModelSearch($query, $lim); 
$this->set('results',$this->Paginate($results)); 

我不能找到一種方法,結果傳遞到分頁程序來渲染分頁結果的看法,除非我通過控制器按第一塊的代碼,這是我一直在說使用它是不好的MVC原則。

回答

1

要創建自定義分頁,你有兩個選擇:

  • 創建一個paginatepaginateCount funtions一個Custom Query Pagination

    //分頁和paginateCount在行爲上實現。 公共函數PAGINATE(型號$模型,$條件,$字段,$順序,$限制, $頁= 1,$遞歸= NULL,$額外=陣列()){// 方法內容 }

    公共函數paginateCount(型號$模型,$條件= NULL,$遞歸= 0,$ 額外=陣列()){// 方法主體 }

  • 或創建custom find並設置Paginator使用該找。

0

好理解,但道理應該告訴我,錯誤打你,你在做什麼。

在「任務」模型中的功能,你不應該把$this->task->find只是$this->find,如果你在模型中不需要指定你正在使用的模型,ou只需要在控制器中做到這一點。

模型/ Task.php:

public function CustomModelSearch($query = null, $lim = null) 
{ 
    return $this->find('all', array(
     'conditions' => array(
      'Customer.site_id LIKE' => '%' . $this->viewVars['shopId'], 
      'CONCAT(Customer.first_name," ",Customer.last_name," ",Customer.organisation) LIKE' => '%' . implode(' ', $tokens) . '%' 
     ), 
     'limit' => $lim 
    )); 
} 
+0

我意識到這一點。發佈的功能只是一個例子來說明我的觀點。 – 2014-10-30 22:21:48

+0

把你的問題說明你的問題和錯誤給您和您的代碼wihtout例子 – CoolLife 2014-10-31 01:13:42