以错误的顺序对删除表进行续集 [英] Sequelize drop table in wrong order

查看:24
本文介绍了以错误的顺序对删除表进行续集的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在我的 nodejs 应用程序中使用 sequelize ORM,当我 sequelize.sync({force: true})

I am using the sequelize ORM in my nodejs app and it seems that it drops table in the wrong order when I 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}) 之后得到以下日志:

I get the following logs after 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

似乎以错误的顺序删除表格.

Seems to be dropping tables in the wrong order.

推荐答案

与 Guest 答案相同,但没有外部要求.

Same answer as Guest but without external requirements.

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

这篇关于以错误的顺序对删除表进行续集的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆