'use strict';
module.exports = {
up: (queryInterface, Sequelize) => {
return Promise.all([
queryInterface.addColumn('Posts', 'userAccountId', {
type: Sequelize.INTEGER,
}),
queryInterface.addColumn('Posts', 'postTopicId', {
type: Sequelize.INTEGER,
}),
queryInterface.addConstraint('Posts', ['userAccountId'], {
type: 'foreign key',
name: 'userAccountId',
references: {
table: 'UserAccounts',
field: 'id',
},
onDelete: 'no action',
onUpdate: 'no action',
}),
queryInterface.addConstraint('Posts', ['postTopicId'], {
type: 'foreign key',
name: 'postTopicId',
references: {
table: 'PostTopics',
field: 'id',
},
onDelete: 'no action',
onUpdate: 'no action',
}),
]);
},
down: (queryInterface, Sequelize) => {
return Promise.all([
queryInterface.removeColumn('Posts', 'userAccountId'),
queryInterface.removeColumn('Posts', 'postTopicId'),
queryInterface.removeConstraint('Posts', 'userAccountId'),
queryInterface.removeConstraint('Posts', 'postTopicId'),
]);
},
};
当我运行命令npx sequelize db:migrate时,出现此错误“错误:外键约束中引用的列“ postTopicId”不存在”
我没有错,所有其他迁移运行正常。 我正在docker容器中运行数据库。
答案 0 :(得分:2)
在执行修改结构并相互依赖的查询时,请勿使用Promise.all
。 Promise.all
不保证执行查询的原始顺序。使用事务和顺序执行:
return queryInterface.sequelize.transaction(async transaction => {
await queryInterface.addColumn('Posts', 'userAccountId', {
type: Sequelize.INTEGER,
}, { transaction })
await queryInterface.addColumn('Posts', 'postTopicId', {
type: Sequelize.INTEGER,
}, { transaction })
await queryInterface.addConstraint('Posts', ['userAccountId'], {
type: 'foreign key',
name: 'userAccountId',
references: {
table: 'UserAccounts',
field: 'id',
},
onDelete: 'no action',
onUpdate: 'no action',
}, { transaction })
await queryInterface.addConstraint('Posts', ['postTopicId'], {
type: 'foreign key',
name: 'postTopicId',
references: {
table: 'PostTopics',
field: 'id',
},
onDelete: 'no action',
onUpdate: 'no action',
}, { transaction })
});