使用cakephp获取消息表mysql中用户之间的唯一对话

时间:2018-01-04 07:41:16

标签: mysql cakephp

我有一个包含以下列的消息表

id | message | toId | fromId | {few more columns}

我正在尝试列出最近的会话列表。考虑一个id为1的i与id为2的聊天

的情况

有些行会像

1 | First Message | 1 | 2 | {few more columns}
2 | Sec   Message | 2 | 1 | {few more columns}
3 | Third Message | 1 | 3 | {few more columns}

以下是我根据消息获取唯一对话的代码

$result = $this->Message->find('all', array(
                    'conditions' => $conditions,       
                     'joins' => array(
                                        array(
                                                'table' => 'users',
                                                'alias' => 'from',
                                                'type' =>  'LEFT',
                                                'conditions' => array(
                                                    'from.id = Message.from',                                                   
                                              )
                                        ),
                                        array(
                                                'table' => 'users',
                                                'alias' => 'to',
                                                'type' =>  'LEFT',
                                                'conditions' => array(
                                                    'to.id = Message.to',                                                   
                                              )
                                        ),
                    ),
                    'fields' => array('from.id','from.firstname','from.username', 'from.lastname','from.imagePath',
                        'to.id','to.firstname','to.username', 'to.lastname','to.imagePath',
                        'Message.*'), 
                    'order' => array('Message.created DESC'),
                    'limit' => 20,
                    'offset' => $offset * 20,                    
        ));

以上代码只是简单地获取所有消息并附加其用户。但是我不知道如何根据独特的对话设置条件。

在上面的示例中,有两个对话,介于1和2之间,介于1和3之间

如何仅列出2条具有唯一组合的响应消息

  

“SELECT FromidFromfirstnameFromusername,   FromlastnameFromimagePathToidTofirstname,   TousernameTolastnameToimagePathMessage。* FROM   xxxxmessages AS Message LEFT JOIN xxxxusers AS To   开(Messageto = Toid)LEFT JOIN xxxxusers AS From   开(Messagefrom = Fromid)LEFT JOIN xxxxmessages AS   message ON(({Messagefrom = messagefromMessageto   = messageto)或(Messagefrom = messagetoMessageto = messagefrom))和Messagecreated<   messagecreated)WHERE messageid IS NULL ORDER BY   Messagecreated DESC LIMIT 20“,

1 个答案:

答案 0 :(得分:1)

要从每个唯一的toId和fromId的消息中获取最新的对话,您可以在on()部分

中使用自连接和一些条件子句
SELECT m.*
FROM 
message m
LEFT JOIN message m1 ON (
  (
    (m.fromId  = m1.fromId  AND m.toId  = m1.toId )
                          OR
    (m.fromId  = m1.toId  AND m.toId  = m1.fromId  )
  )
  AND m.created < m1.created
)
WHERE m1.id IS NULL
ORDER BY m.id

DEMO

稍后,您可以使用上述查询加入用户表以获取用户相关信息