【问题标题】:How to remove associations from the output in Sequelize?如何从 Sequelize 的输出中删除关联?
【发布时间】:2020-03-10 16:12:22
【问题描述】:

我为模型用户定义了一个 classMethod

// model user.js
classMethods: {
    associate: function(models) {
        User.belongsToMany(models.project, {through: 'user_project', foreignKey: 'user_id', otherKey: 'project_id'})
    }
}

从 Express 中的路由中查询该用户的项目并将其输出为 JSON

user.getProjects({
    attributes: ['id', 'title'],
})
.then(function(projects) {
    res.json(projects)
})

这很好用,除了输出还包含我想隐藏/省略/删除的user_project 属性

[
  {
    "id": 8,
    "title": "Some project",
    "user_project": {
       "created_at": "2017-02-16T22:52:48.000Z",
       "updated_at": "2017-02-16T22:52:48.000Z",
       "project_id": 8,
       "user_id": 5
     }
  },
  //etc.

我尝试了各种排除和包含语句,但输出始终包含它。

有没有办法让这个不显示在输出中?

【问题讨论】:

    标签: node.js express sequelize.js


    【解决方案1】:

    我偶然发现了解决方案。

    要从连接表中删除属性,您可以使用joinTableAttributes,如下所示:

    user.getProjects({
        attributes: ['id', 'title'],
        joinTableAttributes: []
    })
    .then(function(projects) {
        res.json(projects)
    })
    

    通过这样做,它将删除user_project表的(见OP)输出,结果是:

    [
      {
        "id": 8,
        "title": "Test Project",
      },
      {
        "id": 4,
        "title": "Another one",
      }
    ]
    

    【讨论】:

    • 酷,很高兴知道
    • 必须承认它被很好地隐藏在sequelize文档中,只有一句话关于joinTableAttributes;)
    【解决方案2】:

    您应该尝试以下方法

     user.getProjects({
        attributes: ['id', 'title'],
        through: {
            attributes: []
        }
    })
    .then(function(projects) {
        res.json(projects)
    })
    

    【讨论】:

    • 我尝试过这种方式,但它仍然将“user_project”显示为响应的一部分。
    • 有趣的是,当我升级到 sequelize@4.0.0-2 时它应该可以工作,但是没有定义“getProjects”。
    • 我在sequelize 4.37.6 上尝试了该方法,但它没有删除连接的属性,实际上只有来自另一个答案的joinTableAttributes 是我正在使用的版本的工作上
    【解决方案3】:

    对我有用的唯一方法是将中间表的 DefaultScope 定义为

    { attributes: [] }

    我正在使用 Sequelize@5

    【讨论】:

      猜你喜欢
      • 2016-11-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-06-10
      • 1970-01-01
      • 2019-09-02
      • 1970-01-01
      • 2017-06-09
      相关资源
      最近更新 更多