Sequelize使用方法—Orm框架
文章目录
1.使用前需要安装的依赖
npm install sequelize -S
npm install mysql2 -S
为了更好的使用Sequelize,官方提供相关的脚手架cli
npm install sequelize-cli -g
2.初始化Sequelize项目
sequelize init
会在当前项目中生成
- config: 数据库配置
- migrations:迁移
- models:模型
- seeders: 种子
3.初始化数据库
sequelize db:create --charset 'utf8mb4'
数据库是根据config文件夹下的config.json中的database字段创建的
{
"development": {
"username": "root",
"password": "root",
"database": "ai_express_development",
"host": "127.0.0.1",
"dialect": "mysql"
}
4.创建表
使用代码来创建表需要用到models模型,而创建模型的时候会自动生成一份migrations迁移文件
sequelize model:generate --name program_name --attributes field1:type,field2:type
示例代码:
sequelize model:generate --name Article --attributes title:string,content:text
生成出的article.js的模型文件,目前项目需求简单,保持不动就好,到时候可直接使用
之后打开migrations迁移文件中的 create-article.js, 里面保存的都是Article的字段
'use strict';
/** @type {import('sequelize-cli').Migration} */
module.exports = {
async up(queryInterface, Sequelize) {
await queryInterface.createTable('Articles', {
id: {
allowNull: false,//不为空
autoIncrement: true, //自增
primaryKey: true,//主键
type: Sequelize.INTEGER//数字类型
},
title: {
type: Sequelize.STRING
},
content: {
type: Sequelize.TEXT
},
createdAt: {
allowNull: false,
type: Sequelize.DATE
},
updatedAt: {
allowNull: false,
type: Sequelize.DATE
}
});
},
async down(queryInterface, Sequelize) {
await queryInterface.dropTable('Articles');
}
};
里面除了title和content以外,还自动生成了id,createAt,updateAt,而这三个字段会自动填充
执行此命令可运行 create-article.js迁移文件,会自动将该表创建至数据库中
sequelize db:migrate
5.将测试数据填充到表
需要用到seed种子文件,执行命令即可创建
sequelize seed:generate --name table_name
点开此种子文件,将 bulkInsert()以及bulkDelete()里的表名换成自己创建的表的名字,在数组里加上对应字段的对象
'use strict';
/** @type {import('sequelize-cli').Migration} */
module.exports = {
async up (queryInterface, Sequelize) {
await queryInterface.bulkInsert('Article', [{
title: '今天天气可真好啊',
content:"狂风暴雨特别凉快哦,欢迎每年来武汉看海! ",
createdAt: new Date(),
updatedAt: new Date()
},{
title: '武汉最好吃的小吃是什么',
content:"狂风暴雨特别凉快哦,欢迎每年来武汉看海! ",
createdAt: new Date(),
updatedAt: new Date()
}], {});
},
async down (queryInterface, Sequelize) {
await queryInterface.bulkDelete('Article', null, {});
}
};
执行此命令即可将测试数据填充至对应表中
sequelize db:seed:all
6.增删改查
在routes或者services中 引入model文件
const models = require('../models')
models.xxx 一定是在models文件夹下的模型的名字
6.1查
6.1.1查询所有
const data = await models.Article.findAll()
6.1.2模糊查询
引入Op
const Op = models.Sequelize.Op
需要给findAll()方法中传入一个对象,需要在此对象里添加where字段,where字段需要接收一个对象
let where = {}
where.title = {
[Op.like]: '%' + title + '%'
}
const data = await models.Article.findAll({
where:where
})
6.1.3根据id查询
findByPk()中的Pk是主键的意思,默认为id
const data = await models.Article.findByPk(id)
6.2增
6.2.1增加
const data = await models.Article.create({
title:"标题",
content:"详情"
})
6.3改
6.3.1根据id修改表
const data = await models.Article.findByPk(id)
data.update(req.body) //将前端传过来的数据进行修改
6.4删
6.4.1根据id删除表
const data = await models.Article.findByPk(id)
data.destory()