【问题标题】:Removing join table data in sequelize returned value在 sequelize 返回值中删除连接表数据
【发布时间】:2020-06-23 08:55:41
【问题描述】:

我目前正在尝试删除在检索关联数据时添加的joint 表数据。

查询是通过指定模型关系(sequelize magic methods)添加到模型的方法通过sequelize完成的,由于某种原因,我无法做到。

我目前尝试将attributes: {exclude: ['...']} 传递给该方法,但该字段仍然存在。

当前关联

// Class sequelize model

Class.belongsToMany(models.Subject, { 
  through: 'ClassSubject', 
  foreignKey: 'class_id', 
  otherKey: 'subject_id', 
  as: 'subjects' 
})


// Subject sequelize model

Subject.belongsToMany(models.Class, { 
  through: 'ClassSubject', 
  foreignKey: 'subject_id', 
  otherKey: 'class_id',
  as: 'classes' 
});

查询和响应

const subjects = await dbClass.getSubjects(); // dbClass is a Class model instance

// Response
[
  {
    "id": "1b89d44c-2caa-452d-a1f8-7faa11970917",
    "name": "Mathematics",
    "code": "MATHS",
    "summary": "Mathematics for class 1",
    "ClassSubject": {
      "class_id": "637afc7b-40f6-478e-b35e-859ca462e2e7",
      "subject_id": "1b89d44c-2caa-452d-a1f8-7faa11970917"
    }
  }
]

期望的输出

// Response
[
  {
    "id": "1b89d44c-2caa-452d-a1f8-7faa11970917",
    "name": "Mathematics",
    "code": "MATHS",
    "summary": "Mathematics for class 1"
  }
]

我已尝试将选项传递给下面指定的方法,但无济于事

const subjects = await dbClass.getSubjects({ 
    attributes: { exclude: ['ClassSubject'] } 
});

但还是不行。

【问题讨论】:

    标签: orm sequelize.js associations


    【解决方案1】:

    尝试使用joinTableAttributes 选项并传递空数组以排除联合表中的所有内容。

    const subjects = await dbClass.getSubjects({ joinTableAttributes: [] }); 
    

    【讨论】:

    • 好的,我会试试的。
    猜你喜欢
    • 2023-04-01
    • 2018-08-29
    • 2020-10-02
    • 1970-01-01
    • 1970-01-01
    • 2015-07-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多