【问题标题】:Sequelize query shows additional data in Many to Many relationshipSequelize 查询在多对多关系中显示附加数据
【发布时间】: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 属性会针对用户拥有的每个主题显示。

我该如何摆脱它?

【问题讨论】:

    标签: mysql node.js database orm sequelize.js


    【解决方案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: []
                  }
              }
          ]
      })
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2016-12-15
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2020-10-31
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多