[英]How can I use a wildcard search to get a list from scaffolding in a CakePHP?
I've got a scaffold built for CakePHP, but need to have a way for users to type in part of a surname into a text box, click a button and for the list of people to be filtered to a wildcard search. 我已经为CakePHP构建了一个脚手架,但是需要一种方法让用户在文本框中输入部分姓氏,单击一个按钮,然后将要过滤的人员列表过滤为通配符搜索。
I'm struggling for example code. 我正在努力争取示例代码。 Does anyone have some?
有人有吗?
You need to look at the findby methods that CakePHP provides. 您需要查看CakePHP提供的findby方法。
in addition to your standard findAll() you have a number of "magic" findby methods which allow you to specify a column in the table to search by: 除了标准的findAll()外,您还有许多“魔术” findby方法,这些方法使您可以指定表中的列以进行搜索:
$this->User->findBySurname($surname);
You also have findBySql(statement) which allows to you use a custom SQL statement. 您还可以使用findBySql(statement)来使用自定义SQL语句。 You could use this to execute a LIKE statement as follows:
您可以使用它来执行LIKE语句,如下所示:
$users = $this->User->findBySql("SELECT * FROM USERS u WHERE u.SURNAME LIKE '%" . $surname . "%' ORDERBY SURNAME");
That will return you a list of matching users which you can then display to the user. 这将为您返回匹配用户的列表,然后您可以将其显示给用户。 It's not the most efficient query, but it works.
它不是最有效的查询,但可以。
views/users/index.ctp 视图/用户/index.ctp
<fieldset>
<legend>Filter users</legend>
<?php
echo $form->create('User', array('action' => 'index'));
echo $form->input('surname', array('div' => false));
echo $form->submit('Filter', array('div' => false));
echo $form->end();
?>
</fieldset>
controllers/users_controller.php controllers / users_controller.php
public function index($surname = null) {
// post-redirect-get
if ($this->data['User']['surname']) {
$this->redirect(array('id' => $this->data['User']['surname']));
}
// conditions
$conditions = null;
if ($surname) {
$conditions = array('surname LIKE' => '%' . $surname . '%');
}
// find
$users = $this->Users->find('all', array('conditions' => $conditions));
// set
$this->set(compact('users'));
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.