安装

npm install sequelize --save
npm install -g sequelize-cli
npm install mysql2 --save

迁移使用

初始化

npx sequelize init

会生成四个文件夹

Config: 数据库配置文件

Models: 数据模型对象配置文件

Migrations: 数据库迁移文件

Seeders: 包含所有种子文件

生成模型

npx sequelize model:generate --name 表名 --attributes 字段名:字段类型,字段名:字段类型,字段名:字段类型,
// 示例
npx sequelize model:generate --name User --attributes username:string,gender:string,age:string

生成表

npx sequelize db:migrate

生成种子数据

生成种子文件

npx sequelize seed:generate --name 文件名称
// 示例
npx sequelize seed:generate --name demo-user

编辑种子文件

'use strict';

/** @type {import('sequelize-cli').Migration} */
module.exports = {
async up(queryInterface, Sequelize) {
/**
*Add seed commands here.
*
* Example:
* await queryInterface.bulkInsert('People', [{
* name: 'John Doe',
* isBetaMember: false
* }], {});
*/
await queryInterface.bulkInsert('Users', [
{
username: "001",
gender: "girl",
age: "18",
createdAt: new Date(),
updatedAt: new Date(),
},
{
username: "002",
gender: "girl",
age: "15",
createdAt: new Date(),
updatedAt: new Date(),
},
])
},

async down(queryInterface, Sequelize) {
/**
* Add commands to revert seed here.
*
* Example:
* await queryInterface.bulkDelete('People', null, {});
*/
}
};

会插入两条数据

插入数据库

npx sequelize db:seed:all

数据操作

model.create()

// 插入用户数据
async insertUser(params) {
return await this.User.create(params)
}

model.destroy()

// 删除用户数据
async deleteUser(id) {
return await this.User.destroy({
where: {
id
}
})
}

model.update()

// 更新用户数据
async updateUser(params, id) {
return await this.User.update(params, {
where: {
id
}
})
}

model.findAll()

// 获取所有的用户数据
async getUserData(params) {
return await this.User.findAll({
where: params
})
}

表操作

添加表字段

创建迁移脚本

npx sequelize-cli migration:generate --name add-col-to-user
// 示例
npx sequelize-cli migration:generate --name 文件名

编辑迁移脚本

'use strict';

/** @type {import('sequelize-cli').Migration} */
module.exports = {
async up(queryInterface, Sequelize) {
/**
* Add altering commands here.
*
* Example:
* await queryInterface.createTable('users', { id: Sequelize.INTEGER });
*/
await queryInterface.addColumn('users', 'email', {
type: Sequelize.STRING,
allowNull: true,
})
},

async down(queryInterface, Sequelize) {
/**
* Add reverting commands here.
*
* Example:
* await queryInterface.dropTable('users');
*/
}
};

执行迁移

npx sequelize-cli db:migrate

更新model文件

'use strict';
const {
Model
} = require('sequelize');
module.exports = (sequelize, DataTypes) => {
class User 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
}
}
User.init({
username: DataTypes.STRING,
gender: DataTypes.STRING,
age: {
type: DataTypes.STRING,
defaults: "18"
},
email: DataTypes.STRING, // 新添加的字段
}, {
sequelize,
modelName: 'User',
});
return User;
};

更新字段

在编辑脚本中使用queryInterface.changeColumn()

删除字段

queryInterface.removeColumn()