CakePHP 3.0:如何在“查询”构建器中创建多个MySQL OR条件

时间:2015-12-03 08:48:12

标签: php mysql cakephp query-builder cakephp-3.x

我正在使用cakePHP 3.0 for REST API。这是MySQL Query。

SELECT group_chat.message_parents
FROM group_chat    
WHERE group_chat.sender_groups = 1 AND group_chat.`status` = 1 AND group_chat.is_blocked = 0
OR group_chat.recever_groups = 1 AND group_chat.`status` = 1 AND group_chat.is_blocked = 0
OR group_chat.sender_groups = 1 AND group_chat.`status` = 1 AND group_chat.is_blocked = 1 AND group_chat.blocked_by = 1
OR group_chat.recever_groups = 1 AND group_chat.`status` = 1 AND group_chat.is_blocked = 1 AND group_chat.blocked_by = 1
GROUP BY group_chat.message_parents
ORDER BY group_chat.modified DESC;

我将其转换为CakePHP 3.0查询构建器功能。

$all_parents = $this->GroupChat->find()->select(['message_parents',])
            ->where(['sender_groups' => $params['group_id'], 'status' => ACTIVE, 'is_blocked' => DEACTIVE, 'blocked_by' => DEACTIVE])
            ->orWhere(['recever_groups' => $params['group_id'], 'status' => ACTIVE, 'is_blocked' => DEACTIVE, 'blocked_by' => DEACTIVE])
            ->orWhere(['sender_groups' => $params['group_id'], 'status' => ACTIVE, 'blocked_by' => $params['group_id']])
            ->orWhere(['recever_groups' => $params['group_id'], 'status' => ACTIVE, 'blocked_by' => $params['group_id']])
            ->order(['modified' => 'DESC'])
            ->group('message_parents');

但它不是像之前的查询那样的产品预期结果。任何帮助都将受到高度赞赏。

更新

debug($all_parents);

Debug会输出这个。

'sql' => '
SELECT GroupChat.message_parents AS `GroupChat__message_parents` 
FROM group_chat GroupChat 
WHERE ((recever_groups = :c0 AND status = :c1 AND is_blocked = :c2 AND blocked_by = :c3) 
  OR (sender_groups = :c4 AND status = :c5 AND is_blocked = :c6 AND blocked_by = :c7) 
  OR sender_groups = :c8 
  OR status = :c9 
  OR blocked_by = :c10 
  OR recever_groups = :c11 
  OR status = :c12 OR blocked_by = :c13) 
GROUP BY message_parents  
ORDER BY modified DESC',

1 个答案:

答案 0 :(得分:0)

您的原始SQL查询没有任何分组。因此,它有效地转换为sHour = document.getElementById('starth').value, sMin = document.getElementById('startm').value, sSec = document.getElementById('starts').value, sTime = (sHour * 3600) + (sMin * 60) + sSec; ed或OR ed:

的每个条件
AND

WHERE group_chat.sender_groups = 1 AND group_chat.`status` = 1 AND group_chat.is_blocked = 0 OR group_chat.recever_groups = 1 AND group_chat.`status` = 1 AND group_chat.is_blocked = 0 OR group_chat.sender_groups = 1 AND group_chat.`status` = 1 AND group_chat.is_blocked = 1 AND group_chat.blocked_by = 1 OR group_chat.recever_groups = 1 AND group_chat.`status` = 1 AND group_chat.is_blocked = 1 AND group_chat.blocked_by = 1 A AND A = A(基本布尔代数)以来,上述内容将减少为:

A OR A = A

这很可能不是你想要的。

您编写的CakePHP查询是分组 WHERE group_chat.sender_groups = 1 OR group_chat.recever_groups = 1 AND group_chat.`status` = 1 AND group_chat.is_blocked = 0 AND group_chat.is_blocked = 1 AND group_chat.blocked_by = 1 AND,这解释了它产生不同结果的原因。