如何在cakephp中只在需要时显示搜索结果?

时间:2011-11-02 09:44:35

标签: cakephp cakephp-1.3

我有以下情况,我想只在用户搜索某些内容时显示搜索结果。当然,当我访问我的搜索页面时,正在显示所有搜索结果,如果用户搜索特定的事物,它会相应地显示。以下是我的搜索控制器中的代码。我为它分页加了一个分页。      function simple_search(){

        $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 个答案:

答案 0 :(得分:1)

你为什么要做这个('全')?稍后几行paginate()会覆盖结果。

为空($ this-&gt; params ['url'] ['value']选中此项并将结果设置为视图,只有在它不为空的情况下。

遵循CakePHP的编码标准并使用camelCased变量名而不是下划线。 http://book.cakephp.org/2.0/en/contributing/cakephp-coding-conventions.html

另外你可能想看看这个。 https://github.com/CakeDC/search

并在此(显示使用搜索插件的custum发现) https://github.com/CakeDC/users/blob/master/controllers/users_controller.php#L316 https://github.com/CakeDC/users/blob/master/models/user.php#L557