我有以下情况,我只想在用户搜索某些内容时显示搜索结果。目前,当我访问搜索页面时,会显示所有搜索结果,如果用户搜索特定内容,它会相应地显示。以下是我的搜索控制器中的代码。我添加了一个分页让它分页。 函数 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);
}
你为什么要查找('all')?几行后 paginate() 会覆盖结果。
empty($this->params['url']['value'] 检查此项并仅在其不为空的情况下将结果设置为视图。
遵循 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