我看到您可以采取三种选择。前两个选项可能是极端情况,但有助于理解。
破坏性选项
您想要为项目制作原型并且不介意丢失数据,那么您可能不关心迁移文件并根据您的模型同步您的数据库:
await sequelize.sync({ force: true });
它将在您的所有模型上执行:
DROP TABLE IF EXISTS "your_model" CASCADE;
CREATE TABLE IF NOT EXISTS "your_model" (...)
例如,此命令可以在您的应用程序启动时执行。
静态选项
正如您提到的,您不想添加列和内容,这可能是一个不错的选择。
现在,如果您不想丢失数据,可以简单地使用不带强制选项的同步方法:
await sequelize.sync({ });
它只会生成:
CREATE TABLE IF NOT EXISTS "your_model" (...)
因此,您的表是根据您的模型创建的,您不必创建迁移文件。
但是,如果您想修改模型并且这是最常见的用例,新列将不会在表中动态生成,这就是您需要迁移脚本的原因。
灵活的选择
您必须同时定义迁移文件和模型。这就是cli 所做的。这是一个例子:
# npx sequelize-cli init or create migrations and models folders
npx sequelize-cli model:generate --name User --attributes firstName:string,email:string
现在您将拥有另外两个文件:
// migrations/<date>-create-user.js
module.exports = {
up: (queryInterface, Sequelize) => {
return queryInterface.createTable('Users', {
id: {
allowNull: false,
autoIncrement: true,
primaryKey: true,
type: Sequelize.INTEGER
},
firstName: {
type: Sequelize.STRING
},
email: {
type: Sequelize.STRING
},
createdAt: {
allowNull: false,
type: Sequelize.DATE
},
updatedAt: {
allowNull: false,
type: Sequelize.DATE
}
});
},
down: (queryInterface, Sequelize) => {
// I usually remove this and create the table only if not exists
return queryInterface.dropTable('Users');
}
};
// models/users.js
module.exports = (sequelize, DataTypes) => {
const User = sequelize.define('User', {
firstName: DataTypes.STRING,
email: DataTypes.STRING
}, {});
User.associate = function(models) {
// associations can be defined here
};
return User;
};
您可以从迁移和模型中重构代码,但这会相当麻烦,因为某些迁移文件只会添加一列,因此将它们全部合并到模型中可能不太清楚。