我有user_messages
列的表id, sender_id, receiver_id, message, deleted
我必须检索所有这样的消息
SELECT *
FROM
user_messages UserMessages
WHERE (
UserMessages.deleted = false
AND (
(sender_id = $loggedin_user_id AND receiver_id = $user_id)
OR
(sender_id = $user_id AND receiver_id = $loggedin_user_id)
)
ORDER BY
created DESC
目前,我正在使用这个查询生成器
$message_by_list = $this->UserMessages->find()
->where(['UserMessages.deleted' => false])
->andWhere(function ($exp) {
return $exp->or_([
'sender_id' => $this->Auth->user('id'),
'receiver_id' => $this->Auth->user('id')
]);
})
生成 sql 查询为
FROM
user_messages UserMessages
WHERE
(UserMessages.deleted = false AND (sender_id = $loggedin_user_id OR receiver_id = $loggedin_user_id))
ORDER BY
created DESC
如何编写优化的 ORM 查询来检索上述数据?
编辑 2:更新了 arilia 答案的查询
WHERE (
(
UserMessages.deleted = false
)
AND
(
(
UserMessages.sender_id = $loggedin_user_id
AND
UserMessages.receiver_id = $user_id
)
OR
UserMessages.sender_id = $user_id
OR /// doubt here
UserMessages.receiver_id = $loggedin_user_id
)
)