用于CakePHP中复杂条件的ORM查询构建器

时间:2017-02-17 08:17:41

标签: mysql cakephp orm cakephp-3.3 selectquerybuilder

我的$str = 'Chicago-Illinos1'; echo ++$str; 表格中包含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

生成sql查询为

$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')
        ]);
    })

如何编写优化的ORM查询以检索上述数据?

  

编辑2:更新了arilia回答的查询

FROM 
    user_messages UserMessages  
WHERE 
    (UserMessages.deleted = false AND (sender_id = $loggedin_user_id OR receiver_id = $loggedin_user_id)) 
ORDER BY 
    created DESC

1 个答案:

答案 0 :(得分: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]);