迁移
(文档)[https://github.com/demopark/sequelize-docs-Zh-CN/blob/v5/migrations.md]
安装 sequelize-cli
npm install --save-dev sequelize-cli
.sequelizerc 配置文件
'use strict';const path = require('path');module.exports = {config: path.join(__dirname, 'database/config.json'),'migrations-path': path.join(__dirname, 'database/migrations'),'seeders-path': path.join(__dirname, 'database/seeders'),'models-path': path.join(__dirname, 'app/model'),};
- 初始化 Migrations 配置文件和目录
npx sequelize init:config
npx sequelize init:migrations
npx sequelize init
config, 包含配置文件,它告诉CLI如何连接数据库models,包含你的项目的所有模型migrations, 包含所有迁移文件seeders, 包含所有种子文件
- 将其改成我们项目中使用的数据库配置
"development": {"username": "root","password": null,"database": "egg-sequelize-doc-default", // 数据库"host": "127.0.0.1", // 地址"dialect": "mysql" // 数据库类型},
- 此时 sequelize-cli 和相关的配置也都初始化好了,我们可以开始编写项目的第一个 Migration 文件来创建我们的一个 users 表了
npx sequelize migration:generate —name=init-users
npx sequelize migration:generate —name User —attributes firstName:string,lastName:string,email:string
如果你的数据库还不存在,你可以调用 db:create 命令. 通过正确的访问,它将为你创建该数据库.
- 添加字段
'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');},};
- 执行 migrate 进行数据库变更
# 升级数据库npx sequelize db:migrate# 如果有问题需要回滚,可以通过 `db:migrate:undo` 回退一个变更# npx sequelize db:migrate:undo# 可以通过 `db:migrate:undo:all` 回退到初始状态# npx sequelize db:migrate:undo:all
- 编写model
'use strict';module.exports = app => {const { STRING, INTEGER, DATE } = app.Sequelize;const User = app.model.define('user', {id: { type: INTEGER, primaryKey: true, autoIncrement: true },name: STRING(30),age: INTEGER,created_at: DATE,updated_at: DATE,});return User;};
- 访问model
// app/controller/users.jsconst Controller = require('egg').Controller;function toInt(str) {if (typeof str === 'number') return str;if (!str) return str;return parseInt(str, 10) || 0;}class UserController extends Controller {async index() {const ctx = this.ctx;const query = { limit: toInt(ctx.query.limit), offset: toInt(ctx.query.offset) };ctx.body = await ctx.model.User.findAll(query);}async show() {const ctx = this.ctx;ctx.body = await ctx.model.User.findByPk(toInt(ctx.params.id));}async create() {const ctx = this.ctx;const { name, age } = ctx.request.body;const user = await ctx.model.User.create({ name, age });ctx.status = 201;ctx.body = user;}async update() {const ctx = this.ctx;const id = toInt(ctx.params.id);const user = await ctx.model.User.findByPk(id);if (!user) {ctx.status = 404;return;}const { name, age } = ctx.request.body;await user.update({ name, age });ctx.body = user;}async destroy() {const ctx = this.ctx;const id = toInt(ctx.params.id);const user = await ctx.model.User.findByPk(id);if (!user) {ctx.status = 404;return;}await user.destroy();ctx.status = 200;}}module.exports = UserController;
- 创建第一个种子
npx sequelize-cli seed:generate --name managers# 同上npx sequelize seed:generate --name managers
- 运行种子 撤销种子
# 运行种子npx sequelize-cli db:seed:all# 如果你想撤消最近的种子npx sequelize-cli db:seed:undo# 如果你想撤消特定的种子npx sequelize-cli db:seed:undo --seed name-of-seed-as-in-data# 如果你想撤消所有的种子npx sequelize-cli db:seed:undo:all
下一个是具有外键的迁移示例. 你可以使用 references 来指定外键:
module.exports = {up: (queryInterface, Sequelize) => {return queryInterface.createTable('Person', {name: Sequelize.STRING,isBetaMember: {type: Sequelize.BOOLEAN,defaultValue: false,allowNull: false},userId: {type: Sequelize.INTEGER,references: {model: {tableName: 'users',schema: 'schema'}key: 'id'},allowNull: false},});},down: (queryInterface, Sequelize) => {return queryInterface.dropTable('Person');}}
.sequelizerc 文件
这是一个特殊的配置文件. 它允许你指定通常作为参数传递给CLI的各种选项:
env: 在其中运行命令的环境
config: 配置文件的路径
options-path: 带有其他参数的 JSON 文件的路径
migrations-path: migrations 文件夹的路径
seeders-path: seeders 文件夹的路径
models-path: models 文件夹的路径
url: 要使用的数据库连接字符串. 替代使用 —config 文件
debug: 可用时显示各种调试信息
初始化项目
# 创建数据库npx sequelize db:create# 创建表npx sequelize db:migrate# 创建默认值npx sequelize db:seed:all
数据回滚
# 如果你想撤消所有的种子npx sequelize-cli db:seed:undo:all# 回退到初始状态npx sequelize db:migrate:undo:all
生成公钥:openssl genrsa -out rsa_private_key.pem 1024
生成私钥: openssl rsa -in rsa_private_key.pem -pubout -out rsa_public_key.pem
命令 参数
如果没有全局安装可以通过npx 来运行
如果没有npx 可以选择全局安装
npm install -g npx
sequelize db:migrate 运行挂起的迁移sequelize db:migrate:schema:timestamps:add 更新迁移表以具有时间戳sequelize db:migrate:status 列出所有迁移的状态sequelize db:migrate:undo 恢复迁移sequelize db:migrate:undo:all 恢复运行的所有迁移sequelize db:seed 运行指定的播种机sequelize db:seed:undo 从数据库中删除数据sequelize db:seed:all 运行每个播种机sequelize db:seed:undo:all 从数据库中删除数据sequelize db:create 创建配置指定的数据库sequelize db:drop 删除配置指定的数据库sequelize init 初始化项目sequelize init:config 初始化配置sequelize init:migrations 初始化迁移sequelize init:models 初始化模型sequelize init:seeders 初始化播种机sequelize migration:generate 生成一个新的迁移文件 [别名:migration:create]sequelize model:generate 生成模型及其迁移 [别名:model:create]sequelize seed:generate 生成一个新的种子文件 [别名:seed:create]--version 显示版本号 [boolean]--help 显示帮助
