我的表格中包含用户之间的消息。
{ message, senderId, receiverId, createdAt, updatedAt, id }
对于给定的用户,我想返回该用户曾经与之交谈过的人员列表,并按最新消息中的最新消息的日期排序。
Person D, Person A, Person C, Person Z, ....
用户列具有以下内容:{ name, createdAt, updatedAt, id }
答案 0 :(得分:0)
查询所有消息,并使用Op.or
查询过滤器查找用户ID与发送方或接收方匹配的记录,然后按createdAt
降序排列。使用raw
避免创建Instance
对象,然后遍历结果并通过减少messages
数组来收集用户ID。
const userId = ???;
const messages = await Message.findAll({
attributes: ['senderId', 'receiverId', 'createdAt'],
where: {
[Op.or]: {
senderId: userId,
receiverId: userId,
},
},
order: [['createdAt', 'DESC']],
raw: true, // get raw since we don't need to bother creating Instances
});
// use an object to collect unique IDs
const userIds = {};
// reduce messages to collect userIds and createdAt
const userIds = messages.reduce((userIds, message) => {
// check the senderId and recieverId
['senderId', 'recieverId'].forEach((column) => {
// if it's not our userId and not already in the list, add it
if (message[column] !== userId && !userIds[message[column]]) {
// you could check things about message.createdAt here, or use JSON for more info
userIds[message[column]] = message.createdAt;
}
});
// return the accumulator
return userIds;
}, {});
console.log('User IDs', userIds);