序列化查询显示多对多关系中的附加数据



我设置了用户和主题之间的多对多关系:

User.belongsToMany(Topic, {through: "UserTopics", timestamps: false});
Topic.belongsToMany(User, {through: "UserTopics", timestamps: false});

我试图得到所有的用户和他们的主题,这个查询做得很好:

User.findAll({
attributes: { exclude: ["password"] },
include: [
{ model: Topic, attributes: ['id', 'name',] }
]
})

输出如下:

[
{
"id": 1,
"firstName": "John",
"lastName": "Doe",
"CNP": "123",
"email": "john@gmail.com",
"validated": false,
"createdAt": "2021-02-15T21:46:52.000Z",
"updatedAt": "2021-02-15T21:46:52.000Z",
"topics": [
{
"id": 1,
"name": "crypto",
"UserTopics": {
"userId": 1,
"topicId": 1
}
},
...
},
...
]

但是问题是,我有,我只是不能弄清楚为什么它发生的是UserTopics属性,显示每个用户的主题。

我如何摆脱它?

感谢天父指出这个页面。实际的做法和他写的有点不同。"through"属性必须位于数组对象内部,如下所示:

User.findAll({
attributes: { exclude: ["password"] },
include: [
{
model: Topic,
attributes: ["id", "name"],
through: {
attributes: []
}
}
]
})

阅读https://sequelize.org/master/manual/advanced-many-to-many.html

如果要从结果中排除关联字段:

User.findAll({
attributes: { exclude: ["password"] },
include: [
{ model: Topic, attributes: ['id', 'name',] }
],
through: {
attributes: []
}
})

最新更新