首页 > 解决方案 > Sequelize:如何获取最新的唯一记录?

问题描述

我有一个包含用户之间消息的表格。

{ message, senderId, receiverId, createdAt, updatedAt, id }

对于给定的用户,我想返回一个用户曾经与之交谈过的人的列表,并按最新消息的日期排序。

Person D, Person A, Person C, Person Z, ....

用户列有这些:{ name, createdAt, updatedAt, id }

标签: sequelize.js

解决方案


查询所有消息并使用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);

推荐阅读