【问题标题】:Simple CakePHP search action简单的 CakePHP 搜索动作
【发布时间】:2014-01-30 11:51:00
【问题描述】:

我想要一个简单的搜索功能,可以在模型的索引页面上搜索当前选定的结果。我创建了一个没有实际表的模型搜索:

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");   
}

问题是分页返回一个模型标记为“搜索”的数组(可以理解,因为 useTable 调用)而不是组或用户,模型正在被搜索。有什么方法可以将分页返回的数组重新标记为正在搜索的模型?另一种方法是修改所有 index.ctp 文件或为每个模型创建一个 results.ctp。

【问题讨论】:

  • 为什么要自己破解?拥抱已经可用的功能(并且采用干净干燥的方法):github.com/CakeDC/search - 它使用 PRG 和您应该使用的良好约定。它还使得向任何控制器添加搜索功能变得更加简单。
  • 是的,我看到了,但它看起来很复杂......我已经在 AppController 中使用一个函数进行了搜索,然后将搜索框/元素放在任何索引页面中,索引页面然后重复用于结果。
  • 它的 3 行代码。这并不比你想要做的更复杂:)

标签: cakephp


【解决方案1】:

我不会仅仅为了搜索而创建另一个模型;这是一个 hack,不可扩展。

过去,我只是使用参数(通常在查询字符串中)来更改条件数组(无论是paginate 操作的普通find 操作)。一个例子:

<?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'));
    }
}

希望以上说明了这种方法。

【讨论】:

  • 我使用了array('OR'=> array('name LIKE '=>$searchTerm, 'descr LIKE '=> $searchTerm)),但仍然返回不匹配的结果.. .
猜你喜欢
  • 1970-01-01
  • 2011-08-29
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-03-23
  • 1970-01-01
  • 2014-04-07
相关资源
最近更新 更多