Sequelize:如何获取最新的唯一记录?

时间:2018-09-28 14:27:50

标签: sequelize.js

我的表格中包含用户之间的消息。

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

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

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

用户列具有以下内容:{ name, createdAt, updatedAt, id }

1 个答案:

答案 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);