我对后缀不是很熟悉,但目前我正在使用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'});
我的问题是,应用程序已经部署和使用了至少两年了。所以已经有很多数据了。我不知道如何在不破坏当前数据或重建数据库的情况下引入这种新的关联。
发布于 2022-04-30 09:57:16
您需要为此创建一个迁移。我假设您已经使用了sequelize(如果不使用,请从npm安装)。
在终端中运行,运行
npx后缀-cli迁移:生成名添加到学校和学生的关联
这将创建一个空迁移文件。用下面的代码填充文件
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");
},
};
创建迁移文件后,转到表定义并添加相应表的关联。
在“学生表”中,添加此关联
school.hasMany(学生,{ foreignKey:“学校_id”,as:“学生学校”,sourceKey:“school_id”});
在“学校表”中,添加此关联
student.belongsTo(学校,{foreignKey:'school_id',targetKey:'school_id',as:'studentSchool'});
完成后,在终端中运行迁移文件
npx后缀-cli db:
还可以在执行此操作之前备份数据(以防万一)
https://stackoverflow.com/questions/72059328
复制相似问题