nodejs中ORM框架sequelize使用

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;
3.2 创建对象Stu.js

                
  • 0
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值