简体   繁体   English

Sequelize 查询在多对多关系中显示附加数据

[英]Sequelize query shows additional data in Many to Many relationship

I have this setup, a many-to-many relationship between Users and Topics:我有这个设置,用户和主题之间的多对多关系:

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

I try to get all the users and their topics, this query does it pretty well:我尝试获取所有用户及其主题,这个查询做得很好:

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

This is what it outputs:这是它的输出:

[
    {
        "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
                }
            },
         ...
     },
     ...
]

But the problem that I have and I just can't figure why it happens is that UserTopics attribute that shows up for every topic a user has.但是我遇到的问题是我无法弄清楚为什么会发生这种情况是 UserTopics 属性会为用户拥有的每个主题显示。

How do I get rid of it?我该如何摆脱它?

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

If you want to exclude assosiation fields from result:如果要从结果中排除关联字段:

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

Thanks fatur for pointing out the page.感谢fatur指出页面。 The actual way to do this is a little bit different than what he wrote.这样做的实际方法与他写的有点不同。 The "through" attribute must be inside the array object, like this: “through”属性必须在数组 object 内,如下所示:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM