2017-02-17 55 views
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 
     ) 
    ) 
+0

是由EDIT2我的代碼生成要獲得查詢或查詢?因爲我得到一個AND,你把'懷疑在這裏',而不是OR – arilia

+0

這是您的代碼生成的查詢 – Gaurav

回答

0

查詢試試這個

$message_by_list = $this->UserMessages->find() 
    ->where(['sender_id' => $user_id, 'receiver_id' => $logged_user_id]) 
    ->orWhere(['sender_id' => $logged_user_id, 'receiver_id' => $user_id]) 
    ->andWhere(['UserMessages.deleted' => false]); 
+0

我對生成的查詢有疑問。在更新後的代碼中檢查「///懷疑」。我認爲它會抓取只匹配一列的記錄 – Gaurav