在已部署的数据库中创建两个表之间的新关系 - sequelize

Create a new relationship between two tables in an already deployed database - sequelize

我对 sequelize 不是很熟悉,但目前我正在使用 Node.js 和 Sequelize,我需要在两个表之间创建一个新的一对多关联。我知道生成关联的代码:

school.hasMany(student,{ foreignKey: 'school_id', as : 'studentSchool', sourceKey: 'school_id'});
student.belongsTo(school, {foreignKey: 'school_id', targetKey : 'school_id', as: 'studentSchool'});

我的问题是该应用程序已经部署并使用了至少 2 年。所以已经有很多数据了。我不知道如何在不破坏当前数据或不必重建数据库的情况下引入这个新关联。

您需要为此创建迁移。 我假设您已经使用 sequelize-cli(如果您没有使用,请从 npm 安装)

在您的终端中,运行

npx sequelize-cli migration:generate --name added-association-to-school-and-student

这将创建一个空的迁移文件。用下面的代码填充文件

module.exports = {
  up: (queryInterface, Sequelize) => {
    return queryInterface.addColumn("students", "school_id", {
      type: Sequelize.DataTypes.INTEGER,
        /*
          The defaultValue below was assigned because by default constraints are set to true.
          This means that all students must belong to a school
          If no school_id is specified, mysql sees that this does not follow the constraints and will opt to delete all records from the database.
          So assign a default value and after this, you can go ahead to manually assign the correct schools.
          ENSURE THAT THE DEFAULT VALUE OF school_id PROVIDED HAS A CORRESPONDING EXISITING RECORD IN THE school TABLE
        */
      defaultValue: 1, // or any other existing value. (This is very important!)
      references: {
        model: "schools",
        key: "school_id",
      },
    });
  },
  down: (queryInterface, Sequelize) => {
    return queryInterface.removeColumn("students", "school_id");
  },
};

创建迁移文件后,转到您的 table 定义并为相应的 tables

添加关联

在学生 Table 中,添加此关联

school.hasMany(student,{ foreignKey: 'school_id', as : 'studentSchool', sourceKey: 'school_id'});

在学校Table,添加这个协会

student.belongsTo(school, {foreignKey: 'school_id', targetKey : 'school_id', as: 'studentSchool'});

完成后,运行 终端中的迁移文件

npx sequelize-cli db:migrate

此外,在执行此操作之前备份数据(以防万一)