0. 初始化项目
npm init
1. 安装 sequelize-cli
安装
npm install --save sequelize-cli sequelize mysql2
如果是postgreps 则安装 pg pg-store
2. 生成 sequelize 目录
node_modules/.bin/sequelize init
执行上面命令,会生成以下几个文件夹:
config:包含一个 config.json 文件
models:包含一个 index.js 文件
migrations:空文件夹
seeders:空文件夹
3. 配置连接数据库的信息
{
"development": {
"username": "root",
"password": "123456",
"database": "database_development",
"host": "127.0.0.1",
"dialect": "mysql"
},
"test": {
"username": "root",
"password": "123456",
"database": "database_test",
"host": "127.0.0.1",
"dialect": "mysql"
},
"production": {
"username": "root",
"password": "123456",
"database": "database_production",
"host": "127.0.0.1",
"dialect": "mysql"
}
}
password 字段是字符串类型,切勿设置为数字类型
4. 创建数据库
node_modules/.bin/sequelize db:create
5. 生成模型文件和迁移文件
node_modules/.bin/sequelize model:generate --name User --attributes firstName:string,lastName:string,email:string
执行上面命令会:
在 models 文件夹里生成一个 user.js 文件
在 migrations 文件夹里生成一个 20190210132709-create-user.js 文件
6. 执行迁移
node_modules/.bin/sequelize db:migrate
7. 生成种子文件
node_modules/.bin/sequelize seed:generate --name demo-user
8. 执行种子文件
node_modules/.bin/sequelize db:seed:all
这里的模型和迁移文件都可以自动手动编写, 模型用于程序使用 迁移和种子文件用于生成数据库结构表和初始化数据使用
一对一,一对多的关系也是在模型中指定的
也可以通过npm install sequelize-cli -g 全局安装 然后sequelize 来执行上述命令
相关命令
sequelize db:migrate Run pending migrations
sequelize db:migrate:schema:timestamps:add Update migration table to have timestamps
sequelize db:migrate:status List the status of all migrations
sequelize db:migrate:undo Reverts a migration
sequelize db:migrate:undo:all Revert all migrations ran
sequelize db:seed Run specified seeder
sequelize db:seed:undo Deletes data from the database
sequelize db:seed:all Run every seeder
sequelize db:seed:undo:all Deletes data from the database
sequelize db:create Create database specified by configuration
sequelize db:drop Drop database specified by configuration
sequelize init Initializes project
sequelize init:config Initializes configuration
sequelize init:migrations Initializes migrations
sequelize init:models Initializes models
sequelize init:seeders Initializes seeders
sequelize migration:generate Generates a new migration file [aliases: migration:create]
sequelize model:generate Generates a model and its migration [aliases: model:create]
sequelize seed:generate Generates a new seed file [aliases: seed:create]
断开数据库的链接
SELECT pg_terminate_backend(pg_stat_activity.pid)
FROM pg_stat_activity
WHERE datname='testdb' AND pid<>pg_backend_pid();