我在我的nodejs应用程序中使用sequelize ORM,当我sequelize.sync({force: true})
时,它似乎以错误的顺序删除了表
例如,使用:
var StationEntity = sequelize.define('Station', {
id: { type: Sequelize.INTEGER, primaryKey: true, allowNull: false},
name: { type: Sequelize.STRING, allowNull: false}
})
var StationSnapshotEntity = sequelize.define('StationSnapshot', {
id: { type: Sequelize.BIGINT, autoIncrement: true, primaryKey: true},
snapshotTimestamp: { type: Sequelize.BIGINT, allowNull: false}
})
StationEntity.hasMany(StationSnapshotEntity, {as: 'Snapshots', foreignKeyConstraint: true, allowNull: false})
我在
sequelize.sync({force: true})
之后得到以下日志:Executing: DROP TABLE IF EXISTS `Stations`;
Executing: DROP TABLE IF EXISTS `StationSnapshots`;
Executing: CREATE TABLE IF NOT EXISTS `StationSnapshots` (`id` BIGINT auto_increment , `snapshotTimestamp` BIGINT NOT NULL, `createdAt` DATETIME NOT NULL, `updatedAt` DATETIME NOT NULL, `StationId` INTEGER, PRIMARY KEY (`id`), FOREIGN KEY (`StationId`) REFERENCES `Stations` (`id`)) ENGINE=InnoDB;
Error: ER_ROW_IS_REFERENCED: Cannot delete or update a parent row: a foreign key constraint fails
似乎是按错误的顺序删除表。
最佳答案
答案与访客相同,但没有外部要求。
db.query('SET FOREIGN_KEY_CHECKS = 0')
.then(function(){
return db.sync({ force: true });
})
.then(function(){
return db.query('SET FOREIGN_KEY_CHECKS = 1')
})
.then(function(){
console.log('Database synchronised.');
}, function(err){
console.log(err);
});