1

正如 Cakephp 的手册所建议的那样,我有一列我想在其上放置“OR”条件以匹配多个值和 AND 条件与其他列。

SQL:

SELECT * FROM site_logs 
WHERE action LIKE "Facebook%" OR action LIKE "Twitter%" AND 
created >= "2013-06-29" 
GROUP BY "ip address"

蛋糕PHP:

$conditions = array(
        'OR' => array(
            'SiteLogs.action like' => 'Facebook%'
            'SiteLogs.action like' => 'Twitter%'
        ),
        'SiteLogs.created >=' => '2013-06-29'
    );
 $this->SiteLogs->find('all',
    'conditions' => $conditions,
    'group'     => 'ip address'
 )

生成的 SQL 仅包含“twitter”数据的记录,因为“OR”数组具有相同键的所有元素,它们将相互覆盖。

生成的 SQL;

SELECT `site_logs`.* FROM `site_logs` 
WHERE `site_logs`.`action` LIKE "Twitter%" AND  
    site_logs`.`created` >= "2013-06-29" 
GROUP BY `site_logs`.`ip address`

我应该怎么做才能从“OR”数组中获取所有值?我错过了什么吗?

4

1 回答 1

1

你要找的是这个。将相似的 OR 子句分别放入它们自己的数组中,以防止键重叠。

$conditions = array(
    'OR' => array(
        array('SiteLogs.action like' => 'Facebook%'),
        array('SiteLogs.action like' => 'Twitter%')
    ),
    'SiteLogs.created >=' => '2013-06-29'
);
$this->SiteLogs->find('all',
    'conditions' => $conditions,
    'group'     => 'ip address'
);

这应该会产生这样的 SQL。每个LIKE条件周围都有一组无关紧要的括号,但这对于 Cake 来说是不可避免的,而且它根本不会影响查询的执行。

SELECT * 
FROM site_logs 
WHERE 
    ((action LIKE "Facebook%") OR (action LIKE "Twitter%"))
    AND created >= "2013-06-29" 
GROUP BY "ip address"
于 2013-06-29T15:26:55.120 回答