Я пытаюсь создать модель Users
с привязкой «многие ко многим», чтобы пользователи могли следить за другими пользователями.В одном запросе я хочу получить Users
, за которым следует текущий пользователь;в другом запросе я хочу получить людей, которые следуют за текущим пользователем.
Это моя Users
модель:
module.exports = (sequelize, Sequelize) => {
const Users = sequelize.define(
'Users',
{
id: {
type: Sequelize.INTEGER,
autoIncrement: true,
primaryKey: true,
},
name: {
type: Sequelize.STRING,
},
},
);
Users.associate = function(models) {
Users.belongsToMany(Users, { as: 'following', through: models.UsersUsers });
};
return Users;
};
Я объявляю UsersUsers
, на всякий случай, если мне нужнодобавьте любое поле:
module.exports = (sequelize, Sequelize) => {
const UsersUsers = sequelize.define(
'UsersUsers',
{}
);
UsersUsers.associate = function(models) {};
return UsersUsers;
};
Затем я запрашиваю Users
как:
models.Users.findOne({
where: {
id: req.params.id,
},
include: [
{
model: models.Users,
as: 'following',
},
],
})
.then((results) => {
return res.send({
User: results,
});
})
.catch((error) => {
return res.send(String(error));
});
И я получаю такой результат:
{
"User": {
"id": 1,
"name": "User1",
"following": [
{
"id": 2,
"name": "User2",
"UsersUsers": {
"UserId": 1,
"followingId": 2
}
},
{
"id": 3,
"name": "User3",
"UsersUsers": {
"UserId": 1,
"followingId": 3
}
},
{
"id": 4,
"name": "User4",
"UsersUsers": {
"UserId": 1,
"followingId": 4
}
}
]
}
}
Теперь вопросы:
В моем текущем запросе как исключить «UsersUsers» из результата?attributes: { exclude: ['UsersUsers'] }
не работает…
Как создать запрос для получения текущего пользователя с пользователями, которые следуют за ним, а не за пользователями, за которыми он следует?
Спасибо!
- РЕДАКТИРОВАТЬ:
Решение вопроса 1. состоит в добавлении through: { attributes: [] }
к включенной модели:
models.Users.findOne({
where: {
id: req.params.id,
},
include: [
{
model: models.Users,
as: 'following',
through: {
attributes: [],
},
},
],
})
.then((results) => {
return res.send({
User: results,
});
})
.catch((error) => {
return res.send(String(error));
});
Еще нерешенный вопрос 2!