2011-11-02 89 views
0

我有以下情況,我想只顯示搜索結果,當用戶搜索的東西。當然,當我訪問我的搜索頁面時,所有的搜索結果都會顯示出來,如果用戶搜索某個特定的東西,它會相應地顯示出來。以下是我的搜索控制器中的代碼。我爲它分頁添加了分頁。 功能simple_search(){如何只在cakephp需要時顯示搜索結果?

 $this->User->recursive = 1; 
     $this->Passion->recursive = 1; 
     $this->User->unBindModel(array('hasMany' => array('Topic','Post')),false); 

     $conditions = array(); 
     $options; 

     $or_conditions = array(); 
     $final_conditions = array(); 
     $search_fields = array('User.firstName', 'User.lastName', 'User.email', 'User.displayName'); //fields to search 'Video.tags','Video.desc' 
     $this->layout = "mainLayout"; 

     $value=''; 

     if(!empty($this->params["url"]["value"])){ 
      $value = $this->params["url"]["value"]; 
     } 

     $searches = explode(" ", $value); 
     foreach ($search_fields as $f) { 
      array_push($conditions, array("$f Like" => "$value%")); 
      for ($i = 0; $i < count($searches); $i++) { 
       if ($searches[$i] != "") { 
        array_push($conditions, array("$f Like" => "$searches[$i]%")); 
       } 
      } 

      array_push($or_conditions, array('OR' => $conditions)); 
      $conditions = array(); 
     } 
     $final_conditions = array('OR' => $or_conditions); 
     $users = $this->User->find('all', $final_conditions); 
     $this->paginate = array( 
      'conditions' => $final_conditions, 
      'limit' => 10 
     ); 
     $users = $this->paginate('User'); 
     $this->set('search_fields', $users); 
    } 

回答

1

你爲什麼要這麼做查找( '全部')?幾行後paginate()覆蓋結果。

空($這個 - > PARAMS [「鏈接」] [「值」]檢查並只有在情況下,它不是空的設定結果的看法。

遵循CakePHP的和使用的編碼標準。駝峯格式的變量名,而不是下劃線http://book.cakephp.org/2.0/en/contributing/cakephp-coding-conventions.html

而且你可能想看看這個 https://github.com/CakeDC/search

而在這(顯示找到俗使用搜索插件) https://github.com/CakeDC/users/blob/master/controllers/users_controller.php#L316 的https:// github上。 COM/CakeDC /users/blob/master/models/user.php#L557