Cakephp 从模型函数分页结果

Cakephp 从模型函数分页结果,cakephp,pagination,Cakephp,Pagination,对于CakePHP2.5 我的控制器中有以下搜索功能 public function search($query = null, $lim = null) { $tokens = explode(" ", $query); $this->Paginator->settings = array( 'conditions' => array( 'Customer.si

对于CakePHP2.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,
        ));
    }
我遇到的问题是,我不能(或不知道如何)在自定义搜索中使用Paginator。有没有办法对自定义函数的结果进行分页

ie,我可以做以下操作:

 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原则。

很好理解,但事实应该告诉我,在您所做的事情中,错误击中了您

“任务”模型中的函数,您不应该将
$this->Task->find
仅仅
$this->find
放在模型中,如果您不需要指定您正在使用的模型,您只需要在控制器中执行此操作

model/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
    ));
}

要创建自定义分页,有两个选项:

  • 创建具有
    paginate
    paginateCount
    功能的

    //对行为实现分页和分页计数。 公共函数分页(模型$Model、$conditions、$fields、$order、$limit、, $page=1,$recursive=null,$extra=array(){ //方法内容 }

    公共函数paginateCount(模型$Model,$conditions=null,$recursive=0, $extra=array()){ //方法体 }

  • 或者创建并设置
    Paginator
    以使用该查找


我知道这一点。函数只是一个例子来说明我的观点。把你的问题解释你的问题和错误给你和你的代码没有例子