I have a simple model with only id in each model, and sometimes when I run the application to create the tables in the database, this error appears:
Unhandled rejection SequelizeDatabaseError: Cannot add foreign key constraint
Sometimes it works and sometimes it fails. I have tried with all the possibilites reading the docs but it happens the same, sometimes it works and sometimes no.
Any idea? The code is below.
Version of sequelize: 4.37.4
const Sequelize = require('sequelize');
const sequelize = new Sequelize('*****', '***', '**', {
host: 'localhost',
dialect: 'mysql',
operatorsAliases: false,
pool: {
max: 5,
min: 0,
acquire: 30000,
idle: 10000
}
})
const H = sequelize.define('H', {
});
const B = sequelize.define('B', {
},{
timestamps: false
});
const V = sequelize.define('V', {
},{
timestamps: false
});
const P = sequelize.define('P', {
},{
timestamps: false
});
H.hasMany(P, { foreignKey: 'ide' });
P.hasMany(V, { foreignKey: 'ide' });
B.hasOne(P, { foreignKey: 'ide' });
H.sync({force: true})
P.sync({force: true})
B.sync({force: true})
V.sync({force: true})
答案 0 :(得分:0)
节点是 async 本身。 sync 命令以异步方式发送到服务器,因此我们无法预测命令的执行顺序。
你可以写成
P.sync({force: true})
.then(() => B.sync({force: true}))
.then(() => V.sync({force: true}))
.then(() => H.sync({force: true}))
或
sequelize.sync({force: true})