$ npm install --save egg-sequelize mysql2
export.sequelize = {
enable:true,
package:'egg-sequelize'
}
config.sequelize = {
dialect:'mysql',
host:'127.0.0.1',
port:'3306',
database:'egg_sequelize_doc_default'
}
npm install --save-dev sequelize-cli
const path = require('path');
module.exports = {
'config': path.resolve('config', 'database.json'),
'models-path': path.resolve('db', 'models'),
'seeders-path': path.resolve('db', 'seeders'),
'migrations-path': path.resolve('db', 'migrations')
}
/*
使用此配置,您将告诉CLI
使用config/database.json文件进行配置设置
使用db/models的模型文件夹
使用db/seeders如播种机文件夹
使用db/migrations作为迁移文件夹
*/
npx sequelize init:config
npx sequelize init:migrations
执行完之后回生成database/config.json文件和database/migrations目录,我们修改一下database/config.json中的内容,将其改成我们项目中使用的数据库配置
{
"mark":"包含配置文件,告诉CLI如何连接数据库",
"development": {
"username": "root",
"password": "Cc1223..",
"database": "egg_sequelize_doc_default",
"host": "127.0.0.1",
"dialect": "mysql"
},
"test": {
"username": "root",
"password": null,
"database": "database_test",
"host": "127.0.0.1",
"dialect": "mysql"
},
"production": {
"username": "root",
"password": null,
"database": "database_production",
"host": "127.0.0.1",
"dialect": "mysql"
}
}
npx sequelize migration:generate --name=init-users
执行完后会在 database/migrations 目录下生成一个 migration 文件(${timestamp}-init-users.js),我们修改它来处理初始化 users 表:
'use strict';
module.exports = {
// 在执行数据库升级时调用的函数,创建 users 表
up: async (queryInterface, Sequelize) => {
const { INTEGER, DATE, STRING } = Sequelize;
await queryInterface.createTable('users', {
id: { type: INTEGER, primaryKey: true, autoIncrement: true },
name: STRING(30),
age: INTEGER,
created_at: DATE,
updated_at: DATE,
});
},
// 在执行数据库降级时调用的函数,删除 users 表
down: async queryInterface => {
await queryInterface.dropTable('users');
},
};
# 升级数据库
npx sequelize db:migrate
# 如果有问题需要回滚,可以通过 `db:migrate:undo` 回退一个变更
# npx sequelize db:migrate:undo
# 可以通过 `db:migrate:undo:all` 回退到初始状态
# npx sequelize db:migrate:undo:all