问题描述
我刚刚开始使用Sequelize和Sequelize CLI
I've just started using Sequelize and Sequelize CLI
由于这是开发时间,所以经常添加和删除列.将新列添加到现有模型的最佳方法是什么?
Since it's a development time, there are a frequent addition and deletion of columns. What the best the method to add a new column to an existing model?
例如,我想为 Todo 模型添加新的列"已完成".我将此列添加到models/todo.js.下一步是什么?
For example, I want to a new column 'completed' to Todo model. I'll add this column to models/todo.js. Whats the next step?
我尝试了sequelize db:migrate
不起作用:没有执行迁移,数据库架构已经更新."
推荐答案
如果您使用的是 sequelize-cli 您需要首先创建迁移.这只是一个文件,告诉引擎如何更新数据库以及在出现问题时如何回滚更改.您应该始终将此文件提交到存储库中
If you are using sequelize-cli you need to create the migration first. This is just a file that tells the engine how to update the database and how to roll back the changes in case something goes wrong. You should always commit this file to your repository
$ sequelize migration:create --name name_of_your_migration
迁移文件如下所示:
module.exports = {
up: function(queryInterface, Sequelize) {
// logic for transforming into the new state
return queryInterface.addColumn(
'Todo',
'completed',
Sequelize.BOOLEAN
);
},
down: function(queryInterface, Sequelize) {
// logic for reverting the changes
return queryInterface.removeColumn(
'Todo',
'completed'
);
}
}
然后运行它:
$ sequelize db:migrate
这篇关于如何在Sequelize CLI中添加,删除新列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!