我想要一个简单的搜索功能,可以在模型的索引页面上搜索当前选定的结果。我创建了一个没有实际表格的模型搜索:
class Search extends AppModel {
protected $_schema = array(
'search_term' => array('type' => 'string' , 'null' => true, 'default' => '', 'length' => '255'),
'model' => array('type' => 'string' , 'null' => true, 'default' => '', 'length' => '255'),
);
public $useTable = false;
public $validate = array(
'search_term' => array(
'notEmpty' => array(
'rule' => array('notEmpty'),
'message' => 'Please enter a search term'
),
'between' => array(
'rule' => array('between',3,30),
'message' => 'Please enter a search term greater than 3 characters.'
)
)
);
}
在任何index.ctp视图中,我都有一个带有模型名称的隐藏输入字段:
echo $this->Form->create('Search, array('action' => 'search'));
echo $this->Form->input('search_term', array('label'=> 'Search'));
echo $this->Form->input('model', array('type'=> 'hidden', 'value'=>$this->params['controller']));
echo $this->Form->end(__('Submit'));
在SearchesController中:
public function search() {
$conditions = null;
if( $this->request->is('post') ) {
$searchModel = $this->request->data[$this->modelClass]['model'];
...
$this->{$this->modelClass}->useTable = Inflector::tableize($searchModel);
...
$this->paginate = array('conditions'=>array($groups,'OR' => $conditions));
$this->set($searchModel, $this->paginate());
$this->render("/$searchModel/index");
}
问题是paginate返回一个标有“Search”模型的数组(可以理解,因为useTable调用),而不是组或用户,正在搜索模型。有什么方法可以将从paginate返回的数组重新标记为正在搜索的模型?另一种方法是修改所有index.ctp文件或为每个模型创建results.ctp。
答案 0 :(得分:1)
我不会仅仅为了搜索而创建另一个模型;这是一个黑客,不可扩展。
过去,我刚刚使用参数(通常在查询字符串中)来改变条件数组(无论它是find
操作的正常paginate
操作。一个例子:
<?php
class ItemsController extends AppController {
public function index() {
$conditions = array();
if (isset($this->request->query['search'])) {
$conditions['Item.title'] = $this->request->query['search'];
}
$items = $this->Item->find('all', array(
'conditions' => $conditions
));
$this->set(compact('items'));
}
}
希望上面演示了这种方法。