Sequlize.max внутри include
Возможно ли получить максимальный id внутри include?
Чтобы вместо этого:
[
{
"id": 1,
"name": "name_1",
"avatar": "avatar_1",
"chats": [
{
"id": 1,
"messages": [
{
"id": 1,
"text": "Привет",
"createdAt": "2021-12-29T08:32:48.000Z",
"updatedAt": "2021-12-29T08:32:48.000Z",
"userId": 1,
"chatId": 1
},
{
"id": 2,
"text": "Приветик",
"createdAt": "2021-12-29T08:32:55.000Z",
"updatedAt": "2021-12-29T08:32:55.000Z",
"userId": 2,
"chatId": 1
},
...
{
"id": 8,
"text": "Пока",
"createdAt": "2021-12-29T08:33:49.000Z",
"updatedAt": "2021-12-29T08:33:49.000Z",
"userId": 1,
"chatId": 1
},
{
"id": 9,
"text": "Пока",
"createdAt": "2021-12-29T08:33:53.000Z",
"updatedAt": "2021-12-29T08:33:53.000Z",
"userId": 2,
"chatId": 1
}
]
}
]
}
]
Получить только один messages с максимальным id:
[
{
"id": 1,
"name": "name_1",
"avatar": "avatar_1",
"chats": [
{
"id": 1,
"messages": [
{
"id": 9,
"text": "Пока",
"createdAt": "2021-12-29T08:33:53.000Z",
"updatedAt": "2021-12-29T08:33:53.000Z",
"userId": 2,
"chatId": 1
}
]
}
]
}
]
Пробовал так:
const chatGroup = await ChatGroup.findAll({
attributes: ['id', 'name', 'avatar'],
include: [{
model: Chat,
where: { userId },
attributes: ['id'],
include: [{
model: Message,
attributes: [sequelize.fn('MAX', sequelize.col('id'))]
}]
}]
return res.json(chatGroup);
});
Но получаю ошибку: Tried to select attributes using Sequelize.cast or Sequelize.fn without specifying an alias for the result, during eager loading. This means the attribute will not be added to the returned instance
Ответы (1 шт):
Автор решения: Alexei
→ Ссылка
Решил так:
const chatGroup = await ChatGroup.findAll({
attributes: ['id', 'name', 'avatar'],
include: [{
model: Chat,
where: { userId },
attributes: ['id'],
include: [{
model: Message,
attributes: ['id', 'text', 'createdAt'],
limit: 1,
order: [['id', 'DESC']]
}]
}]
return res.json(chatGroup);
});