【问题标题】:Non-matching records returned when using OR in CakePHP在 CakePHP 中使用 OR 时返回不匹配的记录
【发布时间】:2014-01-31 11:11:45
【问题描述】:

查询在一个模型上有效,但在另一个模型上却不行......

$this->paginate = array('conditions' => array(
                                array( $model.'group_id' => array(2,3,4) ),
                                'OR' => array('name LIKE ' => "%$searchTerm%",
                                              'desc LIKE ' => "%$searchTerm%",
                                              'modified LIKE ' => "%$searchTerm%")));

我试过不使用组 ID,只使用 searchTerm 和“OR”。但是,当我输入 Foo 时,我仍然会得到 Bar 和 Baz。我检查表格以防 Foo 包含在某处的 Bar/Baz 中,但事实并非如此。所以我的条件一定是错的......

好的,从调试来看,这是实际的查询,当 searchTerm 为 Foo 时返回不匹配的行:

SELECT `User`.`id`, `User`.`username`, `User`.`password`, `User`.`pin`, `User`.`is_ldap`, `User`.`ldap_username`, `User`.`fullname`, `User`.`group_id`, `User`.`password_changed`, `User`.`last_login`, `User`.`status`, `User`.`created`, `User`.`modified`, `Group`.`id`, `Group`.`parent_id`, `Group`.`lft`, `Group`.`rght`, `Group`.`name`, `Group`.`description`, `Group`.`status`, `Group`.`created`, `Group`.`modifed` FROM `crfsystem`.`users` AS `User` LEFT JOIN `crfsystem`.`groups` AS `Group` ON (`User`.`group_id` = `Group`.`id`) WHERE `User`.`group_id` IN (4, 5, 6, 7, 19, 16, 3) AND ((`User`.`username` LIKE '%foo%') OR (`User`.`is_ldap` LIKE '1') OR (`User`.`ldap_username` LIKE '%foo%') OR (`User`.`fullname` LIKE '%foo%') OR (`User`.`password_changed` LIKE '%foo%') OR (`User`.`last_login` LIKE '%foo%') OR (`User`.`status` LIKE '%foo%') OR (`User`.`created` LIKE '%foo%') OR (`User`.`modified` LIKE '%foo%'))

据我所知,在 WHERE 中有有效的“两个”条件:

A and (B or C or D ...)

所以,返回 A 为真且 (..) 为真的行,对吗?但什么是.... 哦!我想我知道...我需要忽略布尔字段,因为无论搜索词如何,它们都会评估为 1/True。

【问题讨论】:

  • 请分享最终输出查询。将 debug 设置为 3 并查看实际查询是什么。
  • debug 2 就足够了 ;) 但数组对我来说看起来不错。应该工作。也许没有匹配的数据?
  • 应该是空白的吧?我已经从调试中复制了查询并粘贴到 phpmyadmin 中并在那里弄乱了它,只使用 OR 条件。还会返回其他不匹配的行。 >_
  • 好的,正在处理查询,似乎某些字段正在触发它。当我在 OR 中只有两个字段时,就像 Foo 一样按预期返回。

标签: mysql cakephp


【解决方案1】:

尝试以下操作:

$this->paginate = array('conditions' => array(
        $model.'group_id' => array(2,3,4),
        'OR' => array(
            array('name LIKE ' => "%$searchTerm%"), 
            array('desc LIKE ' => "%$searchTerm%"), 
            array('modified LIKE ' => "%$searchTerm%")
        )
    )
);

【讨论】:

    【解决方案2】:

    当您对布尔字段执行 LIKE '%searchTerm%' 时,它的计算结果为 true,因此将返回这些行!

    【讨论】:

      猜你喜欢
      • 2011-10-01
      • 2021-07-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2010-09-18
      相关资源
      最近更新 更多