2012-04-18 92 views
0

我在分页搜索结果时遇到问题。我的设置如下。CakePHP:在模型中使用搜索逻辑进行分页

我有一个myapp.com/searches/products与查看(搜索窗体).../app/views/searches/products.ctp的搜索表单。我正在使用Searches控制器,该控制器对此搜索查询使用Product模型。 Product使用搜索逻辑($this->find(...))执行操作search()。搜索结果显示在视图中的表单下方。

我该如何去执行类似于$this->paginate()的操作,这通常是在控制器中完成的?另外,我想知道我的设置是否有问题,特别是包含表单和搜索结果的视图。

回答

3

一个保持模型的搜索逻辑,并在控制器仍然分页方法是做到这一点:

说明:

而是从模型返回的实际结果的,只要返回任何/全部找到选项,然后像通常那样进行分页。对于一些例子,如下面这个简单的例子,它可能看起来有点过分,但它为您的find(),如containorder,group,joins,conditions等等等等增加了更多的选择空间。与“胖模型,瘦控制器”的口头禅。

设置您的find() s这样的选项也很好,因此它可以轻松地在整个网站中重复使用 - 只需传递不同的选项,您就可以轻松前往。

代码:

/* CONTROLLER 
*/ 
$opts = array('paginate' => true, 'limit'=>20); 
$paginateOptions = $this->Event->getEvents($opts); 
$this->paginate = $paginateOptions; 
$data = $this->paginate('Event'); 

/* MODEL 
*/ 
public function getProducts($opts = null) { 

    $params = array(); 

    //limit 
    $params['limit'] = 50; //default 
    if(!empty($opts['limit'])) $params['limit'] = $opts['limit']; 

    //paginate option 
    $paginate = false; 
    if(isset($opts['paginate'])) { 
     if($opts['paginate']) $paginate = true; 
    } 

    //either return the options just created (paginate) 
    if($paginate) { 
     return $qOpts; 

    //or return the events data 
    } else { 
     $data = $this->find('all', $qOpts); 
     return $data; 
    } 
} 

有办法写的代码,这个有点更薄/更小线 - 但是我喜欢这样写它,所以它是快速理解。

(似乎没有要什么不对您的整体结构。)

0

我通常用它来存储在会话搜索参数和处理控制器动作里面的一切。

function indexbystatus() { 
    $this->set('title_for_layout','List Assets by Status'); 
    $this->Session->write('sender',array('controller'=>'assets','action'=>'indexbystatus')); 
    $searchkey=$this->Session->read('Searchkey.status'); 
    $conditions=''; 
    if($searchkey) { 
     $conditions=array('Asset.status_id'=>$searchkey); 
    } 
    if(!empty($this->data)) { 
     // if user has sent anything by the searchform set conditions and 
     // store it to the session but if it is empty we delete the stored 
     // searchkey (this way we can reset the search) 
     if($this->data['Asset']['status_id']!='') { 
      $conditions=array('Asset.status_id'=>$this->data['Asset']['status_id']); 
      $this->Session->write('Searchkey.status',$this->data['Asset']['status_id']); 
     } else { 
      $this->Session->delete('Searchkey.status'); 
      $conditions=null; 
     } 
    } else if($searchkey) { 
     // if no data from the searchform we set the stored one 
     // from the session if any 
     $this->data['Asset']['status_id']=$searchkey; 
    } 
    $this->paginate=array(
         'limit'=>25, 
         'order'=>array('Asset.status_id'=>'asc'), 
         'conditions'=>$conditions, 
         ); 
    $this->set('assets',$this->paginate()); 
    $statuses=$this->Asset->Status->find('list'); 
    $this->set('statuses',$statuses); 
} 

我只是喜欢它更多地处理它在控制器的动作不是模型,所以我可以有通过行动不同的解决方案和逻辑。