0
複雜條件ORM查詢生成器,我有user_messages
表列id, sender_id, receiver_id, message, deleted
在CakePHP的
我要找回這樣
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
)
)
是由EDIT2我的代碼生成要獲得查詢或查詢?因爲我得到一個AND,你把'懷疑在這裏',而不是OR – arilia
這是您的代碼生成的查詢 – Gaurav