首页 > 解决方案 > Sequelize Many to Many Relationship using Through 不会插入额外的属性

问题描述

Step我在:和ControlThrough之间有多对多的关系ControlsConfig。在创建Control对象和调用addStep函数并指定附加属性(存在于关系表中)时,Sequelize 在关系表中创建记录,ControlsConfig 但附加属性为 NULL。

PS:表在数据库中正确创建。

表 1:步骤

表 2:控制

关系表:ControlsConfig

 var Step = sequelize.define('Step', {
    title: { type: DataTypes.STRING, allowNull: false },
    description: DataTypes.STRING,
    type: { type: DataTypes.ENUM('task', 'approval'), allowNull: false, defaultValue: 'task' },
    order: DataTypes.INTEGER
  });

  Step.associate = function(models) {
    models.Step.belongsTo(models.User);
    models.Step.belongsTo(models.Template);
    models.Step.hasMany(models.Action);
  };

控制

var Control = sequelize.define('Control', {
    label: { type: DataTypes.STRING, allowNull: false },
    order: { type: DataTypes.INTEGER },
    type: { type: DataTypes.ENUM('text', 'yes/no') },
    config: { type: DataTypes.TEXT },
    controlUiId: { type: DataTypes.STRING }
  });

  Control.associate = function(models) {
    models.Control.belongsTo(models.Section);
  };

控制配置

  module.exports = (sequelize, DataTypes) => {
  var ControlsConfig = sequelize.define('ControlsConfig', {
    visibility: { type: DataTypes.ENUM('hidden', 'readonly', 'editable', 'required') },
    config: { type: DataTypes.TEXT }
  });

  ControlsConfig.associate = function(models) {
    models.Control.belongsToMany(models.Step, { through: models.ControlsConfig });
    models.Step.belongsToMany(models.Control, { through: models.ControlsConfig });
    models.ControlsConfig.belongsTo(models.Template);
  };

  return ControlsConfig;
};

插入:

try {
    var step1 = await Step.create({ /*bla bla*/ });        
    var control1 = await Control.create({ /*bla bla*/ });    
    var OK = await control1.addStep(step1, {through: { config: 'THIS FIELD ALWAYS APPEARS NULL' }});
  } catch (error) { /* No errors*/ }

我遵循文档中所述的相同策略

//If you want additional attributes in your join table, you can define a model for the join table in sequelize, before you define the association, and then tell sequelize that it should use that model for joining, instead of creating a new one:

const User = sequelize.define('user', {})
const Project = sequelize.define('project', {})
const UserProjects = sequelize.define('userProjects', {
    status: DataTypes.STRING
})

User.belongsToMany(Project, { through: UserProjects })
Project.belongsToMany(User, { through: UserProjects })

//To add a new project to a user and set its status, you pass extra options.through to the setter, which contains the attributes for the join table

user.addProject(project, { through: { status: 'started' }})

标签: sqlnode.jssequelize.js

解决方案


您必须传递edit: true给 addProject 和 addStep 方法。

看到这个答案它有一个类似的问题

Sequelize belongsToMany 连接表中的附加属性


推荐阅读