nodejs中ORM框架sequelize使用
文章目录
一、简介
sequelize是nodejs中基于promise的orm框架,支持mysql、sqlite等。这里以mysql为例,介绍在sequelize在项目中的使用。
二、知识点
2.1 官网地址
文档地址:https://sequelize.org/v5/index.html
github地址:https://github.com/demopark/sequelize-docs-Zh-CN
更多参考地址:http://www.nodeclass.com/api/sequelize.html
2.2 安装
#安装sequelize包
npm install --save sequelize
#安装mysql包
npm install --save mysql2
2.3 语句映射
sequelize中sql操作函数及mysql语句略有不同,映射如下:
mysql关键字 | sequelize函数关键字 |
---|---|
select | find |
update | update |
insert | create |
delete | destory |
2.4 部分关键参数
参数 | 作用 |
---|---|
raw:true | sql语句执行后,只返回原始数据,没有附加信息 |
freezeTableName: true | 定义model时,默认false(即修改表名为复数),true不修改表名,与数据库表名同步 |
如:modelName: ‘Stu’ | 指定model名,相当于sql语句中表的别名,如select * from stu as Stu; 这里Stu即Model |
如:tableName: ‘stu’, | 指定表名,如select * from stu ; |
三、使用示例
这里以orm常规模式流程,介绍sequelize使用。目录结构如下:
------db
| |--sequelize_config.js
|
|--model
| |--Stu.js
|
|--sequelize_main.js
2.1 创建连接sequelize_config.js
const Sequelize = require('sequelize');
const Op = Sequelize.Op;
//配置操作符别称
const operatorsAliases = {
$eq: Op.eq,
$ne: Op.ne,
$gte: Op.gte,
$gt: Op.gt,
$lte: Op.lte,
$lt: Op.lt,
$not: Op.not,
$in: Op.in,
$notIn: Op.notIn,
$is: Op.is,
$like: Op.like,
$notLike: Op.notLike,
$iLike: Op.iLike,
$notILike: Op.notILike,
$regexp: Op.regexp,
$notRegexp: Op.notRegexp,
$iRegexp: Op.iRegexp,
$notIRegexp: Op.notIRegexp,
$between: Op.between,
$notBetween: Op.notBetween,
$overlap: Op.overlap,
$contains: Op.contains,
$contained: Op.contained,
$adjacent: Op.adjacent,
$strictLeft: Op.strictLeft,
$strictRight: Op.strictRight,
$noExtendRight: Op.noExtendRight,
$noExtendLeft: Op.noExtendLeft,
$and: Op.and,
$or: Op.or,
$any: Op.any,
$all: Op.all,
$values: Op.values,
$col: Op.col
};
//创建sequelize
const sequelize = new Sequelize('schema', 'user', 'password', {
host: 'localhost',
dialect: 'mysql',
port: 3306,
pool: {
max: 3,
min: 1,
idle: 8000
},
operatorsAliases
});
module.exports = sequelize;