我正在尝试根据LIKE通配符过滤搜索结果。如果最终用户输入多个关键字,我还想添加几个OR语句。但我的查询返回所有结果而不是过滤结果,下面是代码
function search()
{
$queries = explode(" ", $this->data['Project']['query']);
$nq = '';
foreach($queries as $q)
{
$nq[] = array('Project.project_title LIKE'=>"%$q%");
}
$final = array("OR"=>$nq);
debug($this->Project->find('list',$final));
}
1 SHOW FULL COLUMNS FROM `projects` 28 28 16
2 SELECT CHARACTER_SET_NAME FROM INFORMATION_SCHEMA.COLLATIONS WHERE COLLATION_NAME= 'latin1_swedish_ci'; 1 1 1
3 SHOW FULL COLUMNS FROM `users` 2 2 8
4 SELECT CHARACTER_SET_NAME FROM INFORMATION_SCHEMA.COLLATIONS WHERE COLLATION_NAME= 'utf8_general_ci'; 1 1 1
5 SHOW FULL COLUMNS FROM `categories` 6 6 11
6 SHOW FULL COLUMNS FROM `operating_systems` 2 2 7
7 SHOW FULL COLUMNS FROM `project_operating_systems` 3 3 10
8 SHOW FULL COLUMNS FROM `projects_categories` 3 3 12
9 SELECT `Project`.`id`, `Project`.`project_title` FROM `projects` AS `Project` WHERE 1 = 1 4 4 1
10 SELECT `Category`.`id`, `Category`.`name`, `Category`.`parent_id`, `Category`.`url`, `Category`.`lft`, `Category`.`rght`, `ParentCategory`.`id`, `ParentCategory`.`name`, `ParentCategory`.`parent_id`, `ParentCategory`.`url`, `ParentCategory`.`lft`, `ParentCategory`.`rght` FROM `categories` AS `Category` LEFT JOIN `categories` AS `ParentCategory` ON (`Category`.`parent_id` = `ParentCategory`.`id`) WHERE 1 = 1
答案 0 :(得分:1)
debug($this->Project->find('list',array('conditions'=>$final)));
答案 1 :(得分:0)
在构建一系列or
这样的查询时,请务必将OR
条件括在括号中,否则您将否定AND
条件。
示例:
SELECT *
FROM users
WHERE type='teacher'
只给你老师。
SELECT *
FROM users
WHERE type='teacher'
AND name like '%Joe%'
这只会让教师在名字的某个地方加上“Joe”。但是:
SELECT *
FROM users
WHERE type='teacher'
AND name like '%Joe%'
OR name like '%Mary%'
你可能希望这能给那些名字叫“Joe”或“Mary”的老师......但事实并非如此。它将为您提供名称为“Mary”的任何用户。要更正此问题,请使用括号:
SELECT *
FROM users
WHERE type='teacher'
AND
(name like '%Joe%'
OR name like '%Mary%')