Cakephp问题带有“OR”和“AND”数组与find函数

时间:2013-06-29 14:43:59

标签: cakephp

正如Cakephp的manual建议的那样,我有一个列,我希望将“OR”条件用于匹配多个值,并将AND条件与其他列匹配。

SQL:

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

CakePHP:

$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”数组具有相同键的所有元素,它们将相互覆盖。

GENERATED 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”数组中获取所有值?我错过了什么吗?

1 个答案:

答案 0 :(得分: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"