Sequelize属于连接表中的其他属性

时间:2018-03-09 13:36:55

标签: node.js sequelize.js has-and-belongs-to-many sequelize-cli

我在belongsToMany关系的连接表中遇到其他属性的问题。 在set或add方法中,该属性不会传递给mysql。

我跟随文件传递"通过" set方法中的属性,但它不起作用。 有人知道什么可能是错的,因为以下文档不起作用?

注意:连接的注册和更新是正确的,只有未传递给表的附加属性。

功能模型:

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 }})
    });
  }

OR

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

1 个答案:

答案 0 :(得分:1)

我没有设法通过'set'函数来做到这一点,但是它通过'add'方法为我工作:

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

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

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