如何用Sequelize-cli生成迁移文件及克隆数据库结构生成模型与迁移并填充测试数据
Alright, let's walk through exactly how to handle both of your requirements for setting up your Sequelize-based web app in a clean environment. I'll break this down step by step so it's easy to follow.
Sequelize-CLI doesn't have a one-click command to generate migrations directly from models, but you can do this easily by referencing your model's structure in a new migration file:
- First, make sure Sequelize-CLI is installed (local installation is recommended to avoid global dependency issues):
npm install --save-dev sequelize-cli - If you haven't initialized your Sequelize project yet, run this to create the necessary folders (
config,models,migrations,seeders):npx sequelize-cli init - Place your existing model files (like
users.js) into themodelsdirectory. Double-check that your model has the correcttableNameand attribute definitions. - Generate an empty migration file with a descriptive name (replace
create-userswith something matching your model):npx sequelize-cli migration:generate --name create-users - Open the new migration file in
migrations/. In theupmethod, use your model's raw attributes to define the table structure. For example, if your model isUser:const User = require('../models/user'); module.exports = { up: async (queryInterface, Sequelize) => { await queryInterface.createTable(User.tableName, User.rawAttributes); }, down: async (queryInterface, Sequelize) => { await queryInterface.dropTable(User.tableName); } }; - Run the migration to apply it to your database:
npx sequelize-cli db:migrate
For this, sequelize-auto is perfect for generating models from your live database. Here's how to use it:
Step 1: Install Dependencies
First, install sequelize-auto and your database's driver (replace mysql2 with pg for PostgreSQL, sqlite3 for SQLite, etc.):
npm install --save-dev sequelize-auto mysql2
Step 2: Generate Models from Existing Database
Run sequelize-auto with your database credentials. Important note: If there are existing model files (like users.js) in your target directory, they will be overwritten—backup any files you need to keep first!
Example command for MySQL:
npx sequelize-auto -h localhost -d your_database_name -u your_username -x your_password -p 3306 --dialect mysql -o ./models
-h: Database host-d: Database name-u: Database username-x: Database password (omit if no password)-p: Database port--dialect: Your database type (mysql, postgres, etc.)-o: Output directory for models
Step 3: Generate Migration Files from the Auto-Generated Models
Follow the same process as in requirement 1: generate empty migration files, then reference the auto-generated models' raw attributes to define the table structure. This ensures your migrations match the exact schema from your existing database.
Step 4: Populate Test Data with Seeders
Sequelize seeders let you easily add test data to your database:
- Generate a seeder file with a descriptive name:
npx sequelize-cli seed:generate --name demo-users - Open the seeder file in
seeders/and write code to insert test data. For example:module.exports = { up: async (queryInterface, Sequelize) => { await queryInterface.bulkInsert('Users', [ { username: 'demo_user1', email: 'demo1@example.com', createdAt: new Date(), updatedAt: new Date() }, { username: 'demo_user2', email: 'demo2@example.com', createdAt: new Date(), updatedAt: new Date() } ], {}); }, down: async (queryInterface, Sequelize) => { await queryInterface.bulkDelete('Users', null, {}); } }; - Run the seeder to populate the data:
npx sequelize-cli db:seed:all
Don't forget to update your config/config.json file with your database connection details—this is required for both Sequelize-CLI and sequelize-auto to work correctly.
内容的提问来源于stack exchange,提问作者swiss_knight

