5

我在我的 CakePHP 项目上设置了一个简单的搜索引擎,如下所示:

<?php 
    echo $this->Form->create("Post", array(
        "action" => "search", 
        "id" => "searchForm"
    ));
    echo $this->Form->input("keyword", array(
        "label" => "",
        "type" => "search",
        "placeholder" => "Recherche..."
    ));
    echo $this->Form->end(); 
?>

这是控制器:

function search() {
    $keyword = $this->request->data;
    $keyword = $keyword["Post"]["keyword"];
    $cond = array("OR" => array(
        "Post.title LIKE '%$keyword%'",
        "Post.description LIKE '%$keyword%'"
    ));
    $posts = $this->Post->find("all", array("conditions" => $cond));
    $this->set(compact("posts", "keyword"));
}

而且效果很好。唯一的问题是当我想对结果进行分页时。我只是添加:

$posts = $this->paginate();

这就是问题所在。当我添加这个时,CakePHP 会给我所有的帖子,而不仅仅是那些与关键字匹配的帖子。

因此,如果您有解决方案,那就太好了:)

4

3 回答 3

13

根据 CakePHP book 你应该可以做到

$this->paginate('Post', array(
    'OR' => array(
        'Post.title LIKE' => "%$keyword%",
        'Post.description LIKE' => "%$keyword%"
    )

));

或者你可以这样做(来自 cakephp 站点)。

public function list_recipes() {
    $this->paginate = array(
        'conditions' => array('Recipe.title LIKE' => 'a%'),
        'limit' => 10
    );
    $data = $this->paginate('Recipe');
    $this->set(compact('data'));
);

来源: http ://book.cakephp.org/2.0/en/core-libraries/components/pagination.html

于 2012-12-13T15:04:24.217 回答
0

Paginate 对我相信的数据进行自己的查找。您之前调用的find对 没有影响paginate

试试这个:

$this->paginate = array( 'conditions' => $cond, ));
于 2012-12-13T15:05:22.720 回答
0

您可以首先使用 Session 来存储条件
,当您提交表单时,您将条件存储到 Session
中,然后(分页)您可以从 Session 中读取条件

example i want to search the products:
Products/search.ctp
<?php
    echo $this->Form->create('Product');
    echo $this->Form->input('keyword');
    echo $this->Form->end(__('Search'));
?>
ProductsController.php
<?php 
class ProductsController extends AppController{

public function search() {
        if ($this->request->is('post')) {
            $keyword = $this->request->data['Product']['keyword'];
            $this->paginate = array(
                'fields' => array('Product.name', 'Product.price', 'Product.created'),
                'order' => array('Product.created' => 'DESC', 'Product.price' => 'DESC'),
                'limit' => 30,
                'conditions' => array('Product.name LIKE' => '%' . $keyword . '%')
            );
            // store array $this->paginate into Session
            $this->Session->write('paginate', $this->paginate);
        }
        $this->paginate = $this->Session->read('paginate');
        $this->set('products', $this->paginate('Product'));
    }
}
于 2014-08-03T07:56:23.450 回答