Я использую cakePHP 3.0 для 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');
Но это не дает ожидаемых результатов, как Query раньше. Любая помощь будет высоко оценена.
Обновить:
debug($all_parents);
Отладка выведет это.
'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',
Ваш необработанный SQL-запрос не имеет группировки. Таким образом, это эффективно переводит на каждое состояние OR
ред или 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
(основная булева алгебра) приведенное выше сводится к:
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
Что, скорее всего, не то, что вы хотели.
Написанный вами запрос CakePHP: группировка AND
с и OR
и это объясняет, почему это дает разные результаты.
Других решений пока нет …