【发布时间】:2019-08-08 01:49:52
【问题描述】:
我正在尝试创建一个模型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!
【问题讨论】:
-
你能举一个问题2的例子更清楚吗?
-
谢谢@ChuongTran:我认为当前的例子——用户关注用户——是最好的例子。尝试实现它,你会立即看到它;)
标签: javascript orm sequelize.js