Sequelize 是一个基于 promise 的 Node.js ORM, 目前支持 Postgres, MySQL, MariaDB, SQLite 以及 Microsoft SQL Server. 它具有强大的事务支持, 关联关系, 预读和延迟加载,读取复制等功能。
Sequelize来帮助我们跟踪数据库的更改,并在各个不同时期的数据库状态之间进行切换
其模型Model的理解类似于MongoDB
可以使用sequelize-cli 进行相关命令操作
可以使用Sequel Pro查看数据库。
新建文件夹 test-sequelize ,通过命令行工具进入该文件夹下
npm init -y
会生成一个package.json
1. 安装
npm i sequelize-cli --save-dev
sequelize-cli 的依赖是 sequelize , sequelize的依赖是mysql2 需要自己手动安装
然后安装
npm i sequelize
我要用mysql演示 安装mysql2
npm i mysql2
我们是局部安装所以执行时需要这样
./node_modules/.bin/sequelize-cli --version
# 或者
./node_modules/.bin/sequelize --version
利用npx可以这样子写(npx教程)
sequelize-cli --version
# 或者
sequelize --version
先执行看看所有命令了解
sequelize
2. 初始化
sequelize init
初始化sequelize项目,该命令将创建如下目录:
- config:包含配置文件,它告诉CLI如何连接数据库
- models:包含您的项目的所有模型
- migrations:包含所有迁移文件 (数据表结构) 执行迁移命令后,数据库就有了相关表
- seeders:包含所有种子文件 (具体数据)
优先打开config下的config.json
{
"development": {
"username": "root",
"password": "123456",
"database": "list",
"host": "127.0.0.1",
"dialect": "mysql",
"operatorsAliases": false
},
"test": {
"username": "root",
"password": null,
"database": "database_test",
"host": "127.0.0.1",
"dialect": "mysql",
"operatorsAliases": false
},
"production": {
"username": "root",
"password": null,
"database": "database_production",
"host": "127.0.0.1",
"dialect": "mysql",
"operatorsAliases": false
}
}
配置在不同环境下数据库连接和密码 dialect 是你要操作的数据库类型,当前我使用的是mysql, 默认当前环境为开发环境
config.json配置完成
3. 创建数据库和删除数据库
npx sequelize db:create
会根据你config.json 中添加的数据名称创建
出师不利,立马报错了。如下显示。就是告诉你这个版本不需要这条。请删掉
那就删除config.json中的
"operatorsAliases": false
再执行。成功创建
执行删除
npx sequelize db:drop list
4. 创建模型文件 model
model:generate / model:create
创建一个模型文件
-- name:模型名称,必须
-- attributes:字段列表,必须
新建一个表名为user 字段有username 和sex的表模型,运行以下命令
sequelize model:generate --name student --attributes name:string,sex:string,description:text
- 在 models 文件夹中创建了一个 student 模型文件(供程序使用)
- 在 migrations 文件夹中创建了一个名字像 xxxxxxxx-create-student.js 的迁移文件(供迁移使用)
models下的student.js 文件
'use strict';
const {
Model
} = require('sequelize');
module.exports = (sequelize, DataTypes) => {
class student extends Model {
/**
* Helper method for defining associations.
* This method is not a part of Sequelize lifecycle.
* The `models/index` file will call this method automatically.
*/
static associate(models) {
// define association here
}
}
student.init({
name: DataTypes.STRING,
sex: DataTypes.STRING,
description: DataTypes.TEXT
}, {
sequelize,
modelName: 'student',
});
return student;
};
migrations下的20230410024851-create-student.js
'use strict';
/** @type {import('sequelize-cli').Migration} */
module.exports = {
async up(queryInterface, Sequelize) {
await queryInterface.createTable('students', {
id: {
allowNull: false,
autoIncrement: true,
primaryKey: true,
type: Sequelize.INTEGER
},
name: {
type: Sequelize.STRING
},
sex: {
type: Sequelize.STRING
},
description: {
type: Sequelize.TEXT
},
createdAt: {
allowNull: false,
type: Sequelize.DATE
},
updatedAt: {
allowNull: false,
type: Sequelize.DATE
}
});
},
async down(queryInterface, Sequelize) {
await queryInterface.dropTable('students');
}
};
文件虽然建完了,但是数据库里却啥也没有
需要执行以下命令才能写入数据库
也就是我们核心要做的执行迁移
5. 执行迁移
所谓迁移,就是对数据库进行结构的创建,修改等操作,也就是利用model中的结构在数据库中生成表
db:migrate
- 会在数据库中创建一个 SequelizeMeta 表,用于记录每次的迁移记录
- 执行 migrations 文件下的满足条件(SequelizeMeta表)的脚本
sequelize db:migrate
看数据库
而且还多了一个SequelizeMeta的表记录迁移记录
如果再执行一次迁移文件会不会对数据库造成更改呢?答案是否定的,不会的
看一下当前状态
sequelize db:migrate:status
既然能写入一定还能恢复,否则就失去意义了
6.回退迁移操作
撤销迁移
db:migrate:undo - 撤销上一次的迁移操作
db:migrate:undo:all - 撤销所有的迁移操作
db:migrate:undo --name 具体迁移脚本
sequelize db:migrate:undo
重要: 如果当前文件未被执行过,状态为down 执行过则为 up
当你执行迁移时执行的是迁移js文件中的,up函数。反之则是down函数 (这里可以仔细看一下migrations文件夹下的文件具体函数)
迁移文件和种子文件都是有工具初始化,自己编写
queryInterface文档: sequelize.org/master/clas…
包括增加字段,删除字段,还有种子文件要用到增加数据等
举例说明
先执行了刚才的迁移文件
这是当前sdudent表里的结构
我们现在要添加一个字段 age
新建一个迁移文件
sequelize migration:create --name country
打开生成的这个js文件 改写
'use strict';
module.exports = {
up: (queryInterface, Sequelize) => {
/*
Add altering commands here.
Return a promise to correctly handle asynchronicity.
Example:
return queryInterface.createTable('students', { id: Sequelize.INTEGER });
*/
return queryInterface.addColumn('sdudents', 'country', Sequelize.STRING);
},
down: (queryInterface, Sequelize) => {
/*
Add reverting commands here.
Return a promise to correctly handle asynchronicity.
Example:
return queryInterface.dropTable('students');
*/
return queryInterface.removeColumn('students', 'country', Sequelize.STRING);
}
};
执行迁移操作
sequelize db:migrate
成功
queryInterface文档: sequelize.org/master/clas…
7. 种子文件
种子文件
迁移文件是用来构建数据库以及表结构的,种子文件是用来构建数据的
seed:generate --name demo-user (自定义的名字)
种子文件脚本与迁移脚本类似,由up于down函数组成,传入的参数也是一致的
先生成种子文件 name 后边接的是自定义的名字
sequelize seed:generate --name studentseed
打开刚才的xxxxx-studentseed.js这个文件
'use strict';
module.exports = {
up: (queryInterface, Sequelize) => {
/*
Add altering commands here.
Return a promise to correctly handle asynchronicity.
Example:
return queryInterface.bulkInsert('People', [{
name: 'John Doe',
isBetaMember: false
}], {});
*/
},
down: (queryInterface, Sequelize) => {
/*
Add reverting commands here.
Return a promise to correctly handle asynchronicity.
Example:
return queryInterface.bulkDelete('People', null, {});
*/
}
};
是空的,想要添加数据需要自己写
测试添加一条数据
'use strict';
module.exports = {
up: (queryInterface, Sequelize) => {
return queryInterface.bulkInsert('students', [{
name: 'John Doe',
sex: 'man',
country: 'China',
createdAt: '2023-04-09 11:56:21',
updatedAt: '2020-04-09 11:56:21'
}], {});
},
down: (queryInterface, Sequelize) => {
return queryInterface.bulkDelete('users', null, {});
}
};
执行种子, 可使用的命令如下:
db:seed 指定种子文件 运行指定种子文件
db:seed:all 运行所有种子文件
现在执行命令
sequelize db:seed:all
查看数据库
8. 撤销种子执行
db:seed:undo --seed 指定种子文件 撤销指定种子文件
db:seed:undo:all 撤销所有种子文件
npx sequelize db:seed:undo:all
数据库中刚才添加的数据不见了。
9.种子存储记录
存储记录
默认情况下seed不记录过程,如果需要记录则需要单独设置,在配置文件config.json中增加
seederStorage
存储引擎:none、json、mongodb、sequelize
seederStoragePath 存储路径(json有效)
seederStorageTableName 存储表名,mongodb和sequelize有效
举一个例子
config.json
{
"development": {
"username": "root",
"password": "123456",
"database": "list",
"host": "127.0.0.1",
"dialect": "mysql",
"seederStorage": "json",
"seederStoragePath": "./seeder.json"
},
"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"
}
}
然后我们在执行种子文件
sequelize db:seed:all
这时候多出个文件
打开seeder.json
[ "20200605031821-userseed.js"]
这个类似于我们SequelizeMeta表中的内容
好了,关于sequelize-cli命令的使用,就是上述
ps:
1, mysql数据库需安装,需注意系统环境与mysql版本的匹配,否则Mysql server可能不能正常启动
2,Sequel Pro 是类似于pl-sql的工具,主要用于查看数据库的工具,像mysql workbench,但是感觉比workbench好用
3,相关文章如下: