Sequelize 查询在多对多关系中显示附加数据
Posted
技术标签:
【中文标题】Sequelize 查询在多对多关系中显示附加数据【英文标题】:Sequelize query shows additional data in Many to Many relationship 【发布时间】:2021-05-18 20:01:18 【问题描述】:我有这个设置,用户和主题之间的多对多关系:
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 属性会针对用户拥有的每个主题显示。
我该如何摆脱它?
【问题讨论】:
【参考方案1】:阅读此https://sequelize.org/master/manual/advanced-many-to-many.html
如果您想从结果中排除关联字段:
User.findAll(
attributes: exclude: ["password"] ,
include: [
model: Topic, attributes: ['id', 'name',]
],
through:
attributes: []
)
【讨论】:
【参考方案2】:感谢fatur 指出页面。 这样做的实际方法与他写的有点不同。 “through”属性必须在数组对象内部,像这样:
User.findAll(
attributes: exclude: ["password"] ,
include: [
model: Topic,
attributes: ["id", "name"],
through:
attributes: []
]
)
【讨论】:
以上是关于Sequelize 查询在多对多关系中显示附加数据的主要内容,如果未能解决你的问题,请参考以下文章