我有以下的方法,這需要查詢來搜索我的筆記:在CakePHP的2.x中使用命名參數
function search($q = null)
{
if ($q == null)
{
$this->redirect(array('action' => 'index'));
}
$this->paginate = array(
'limit'=>5,
'order'=>'Note.datetime DESC',
'conditions' => array(
'OR' => array(
'Note.title LIKE' => '%'. $q . '%',
'Note.content LIKE' => '%'. $q . '%'
)
),
'Note.status'=>1
);
$this->set('notes', $this->paginate());
$this->render('index');
}
正如你可以看到它採用所謂的「Q」一個參數是用來查詢模型數據。
我已經迷上了這個路由器像這樣:
Router::connect('/notes',
array('controller'=>'notes','action'=>'index', 'page' => 1),
array(
'pass' => array('page')
)
);
Router::connect('/notes/page/:page',
array('controller' => 'notes', 'action' => 'index'),
array(
'pass' => array('page'),
'page' => '[1-9]+'
)
);
Router::connect('/notes/search/:page/:q',
array('controller'=>'notes','action'=>'search', 'page' => 1),
array(
'pass' => array('page','q')
)
);
Router::connect('/notes/search/:q/page/:page',
array('controller' => 'notes', 'action' => 'search'),
array(
'pass' => array('page','q'),
'page' => '[1-9]+'
)
);
這樣我應該是越來越網址,如:
domain.com/notes - loads page 1 of notes
domain.com/notes/page/2 - loads page 2 of notes
domain.com/notes/search/Hello - searches for Hello in notes
domain.com/notes/search/Hello/page/2 - shows page 2 of the above search
視圖中的尋呼機的樣子:
<?php if(isset($this->request->params['named']['q'])) { ?>
<?php $this->Paginator->options(array('url'=>array('controller' => 'notes', 'action' => $action, 'q' => $this->request->params['named']['q']))); ?>
<?php } else { ?>
<?php $this->Paginator->options(array('url'=>array('controller' => 'notes', 'action' => $action))); ?>
<?php } ?>
它工作正常的索引方法,但是對於搜索方法時感到困惑,當我做它不匹配的尋呼機搜索與預期的路線。例如,我得到的url像domain.com/notes/search/2/:q
另外我真的不喜歡不得不將paginator選項包裝在if語句中,所以如果我可以自動找出url,那會很棒,因爲它很混亂要做到這一點,似乎是造成上述問題的原因。
我已經連接了命名參數在路由器的頂部像這樣:
Router::connectNamed(array('q'));