Sequelize belongsToMany additional attributes in join table

Sequelize belongsToMany additional attributes in join table

我在 belongsToMany 关系的联接 table 中遇到附加属性问题。 在设置或添加方法中,此属性未传递给 mysql.

我正在关注文档传递作为 "through" set 方法中的属性,但它不起作用。 由于遵循文档不起作用,有人知道可能出了什么问题吗?

注意:join的注册和更新是正确的,只是没有传递给table的附加属性。

功能模型:

export default function(sequelize, DataTypes) {
  const Functionality = sequelize.define('functionality', {
    id: {
      type: DataTypes.INTEGER(11),
      allowNull: false,
      primaryKey: true,
      autoIncrement: true
    },
    name: {
      field: 'name',
      type: DataTypes.STRING(300),
      allowNull: false
    }
  }, {
    classMethods: {
      associate: function(models) {
        Functionality.belongsToMany(models.privilege, { as: 'privilegies', through: models.functionality_privilege, foreignKey: 'functionality_id' });
      }
    },
    tableName: 'functionality',
    freezeTableName: true,
    timestamps: true,
    createdAt: 'createdAt',
    updatedAt: 'updatedAt'
  });
  return Functionality;
}

权限模型:

export default function(sequelize, DataTypes) {
  const Privilege = sequelize.define('privilege', {
    id: {
      type: DataTypes.INTEGER(11),
      allowNull: false,
      primaryKey: true,
      autoIncrement: true
    },
    name: {
      field: 'name',
      type: DataTypes.STRING(300),
      allowNull: false
    }
  }, {
    classMethods: {
      associate: function(models) {
        Privilege.belongsToMany(models.functionality, { as: 'functionalities', through: models.functionality_privilege, foreignKey: 'privilege_id' });
      }
    },
    tableName: 'privilege',
    freezeTableName: true,
    timestamps: true,
    createdAt: 'createdAt',
    updatedAt: 'updatedAt'
  });
  return Privilege;
}

功能特权模型:

export default function(sequelize, DataTypes) {
  const Functionalityprivilege = sequelize.define('functionality_privilege', {
    id: {
      type: DataTypes.INTEGER(11),
      allowNull: false,
      primaryKey: true,
      autoIncrement: true
    },
    edit: {
      field: 'edit',
      type: DataTypes.BOOLEAN
    }
  }, {
    tableName: 'functionality_privilege',
    freezeTableName: true,
    timestamps: true,
    createdAt: 'created_at',
    updatedAt: 'updated_at'
  });
  return Functionalityprivilege;
}

创建方法:

create(options) {
    let obj = options.payload;
    return this.functionalityDao.create(obj)
    .then((result) => {
      return result.setPrivilegies(obj.privilegies, { through: { edit: obj.permissions }})
    });
  }

return result.setPrivilegies(obj.privilegies, { through: { edit: true }})

我没能用 'set' 函数做到这一点,但它对我有用 'add' 方法:

result.addPrivilege(privilege, { through: { edit: true }});

它应该适用于已经存在的权限。它不适用于实体数组(在您的情况下是特权),因此我不得不多次调用 'add' 方法。像这样:

return Promise.all(
  privileges.map(privilege =>  result.addPrivilege(privilege, { through: { edit: true }}));
)