sequelize.js - Sequelize:如何获取最新的唯一记录?
问题描述
我有一个包含用户之间消息的表格。
{ message, senderId, receiverId, createdAt, updatedAt, id }
对于给定的用户,我想返回一个用户曾经与之交谈过的人的列表,并按最新消息的日期排序。
Person D, Person A, Person C, Person Z, ....
用户列有这些:{ name, createdAt, updatedAt, id }
解决方案
查询所有消息并使用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);
推荐阅读
- python - shell stdout PYTHON 处理比 PYTHON txt 文件处理慢得多
- ios - 在轴图 ios 上同时使用字符串和日期
- excel - VBA 使用 COUNTIFS 作为公式
- python - 退出代码 -1 的含义
- python - 如何使用 pathlib.Path().glob() 读取文件并将具有相同文件名的文件输出到另一个子文件夹
- .net-core - 如何从现有数据库创建迁移
- python - 无法在 python 中加载 csv 文件
- php - 通过 get_post_meta() 获取产品插件信息
- javascript - 合并包含数组的对象数组
- json - 将 Json 转换为 Avro 架构