我在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会给我所有帖子,而不仅仅是那些与关键字匹配的帖子。
所以,如果你有一个解决方案,那就太好了:)
答案 0 :(得分:12)
根据CakePHP的书,你应该可以做到
$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
答案 1 :(得分:0)
Paginate对我认为的数据进行自己的查询。您之前调用的find
对paginate
无效。
试试这个:
$this->paginate = array( 'conditions' => $cond, ));
答案 2 :(得分:0)
您可以使用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'));
}
}