Nodejs ORM框架Sequelize

(模型,关联表,事务,循环,及常见问题)

建立连接

const Sequelize = require('sequelize');
const sequelize = new Sequelize('database', 'username', 'password', {host: 'host',port: 'port',pool: {max: 50,min: 0,//建立连接最长时间acquire: 30000,//空闲最长连接时间idle: 10000},//默认输出执行sql语句logging: console.log,define: {//默认创建表有 createAt, updateAttimestamps: false,//可以给表设置别名freezeTableName: true,// 字段以下划线(_)来分割(默认是驼峰命名风格)underscored: false},//sequelize v4 必须设置方言dialect: 'mysql',//默认DECIMAL and NEWDECIMAL 返回 StringdialectOptions: {decimalNumbers: true},//设置别名,否则不识别$like等关键词($like: Op.like对应关系)operatorsAliases: 'object',//时间上的统一timezone: "+08:00",
})

模型定义

const DataTypes = Sequelize.DataTypes;
const user = sequelize.define('u', {userId: {type: DataTypes.INTEGER,primaryKey: true,autoIncrement: true},userName: {type: DataTypes.STRING,allowNull: true},birthDay: {type: 'TIMESTAMP',allowNull: false},gender: {type: DataTypes.INTEGER,allowNull: true,defaultValue: 0},ctime: {type: 'TIMESTAMP',allowNull: false,defaultValue: Sequelize.literal('CURRENT_TIMESTAMP')},updatedAt: {type: 'TIMESTAMP',defaultValue: Sequelize.literal('CURRENT_TIMESTAMP'),field: 'ctime'}
}, {tableName: 'user'})const products = sequelize.define('p', {prdId: {type: DataTypes.INTEGER,primaryKey: true,autoIncrement: true},prdName: {type: DataTypes.STRING,allowNull: false},userId: {type: DataTypes.INTEGER,allowNull: false},price: {type: DataTypes.DECIMAL(5, 4),allowNull: false}
})
products.belongsTo(user, { foreignKey: 'userId', targetKey: 'userId', as: 'u' });

注意点:
1. type如果不存在则直接用字符串表示 如:’TIMESTAMP’;
2. 如果需要在更新表字段时记录更新时间,可应使用updateAt,并设置默认值和对应的字段名。
3. 如果默认值不是具体的数值,可以用literal函数去表示。
4. tableName 表名, u为别名。
5. 建立关联关系时,如果外键关联的是主键则不用写targetKey,否则需要。

查询数据

products.findAll({attributes: ['prdName', 'price'],include: [{model: user,as: 'u',attributes: ['userName']}],//raw:true
}).then(result => {console.log(JSON.stringify(result))
}).catch(err => {console.log(err)
})

//结果1:

[{"prdName": "ipad","price": 4.99,"u": { "userName": "张三" }},{"prdName": "iphone","price": 3.658,"u": { "userName": "张三" }},{"prdName": "联想笔记本","price": 9.32,"u": { "userName": "李四" }}
]

我们换个写法

products.findAll({attributes: ['prdName', 'price'],include: [{model: user,as: 'u',attributes: ['userName']}],raw:true
}).then(result => {console.log(JSON.stringify(result))
}).catch(err => {console.log(err)
})

结果2

[{"prdName":"ipad","price":4.99,"u.userName":"张三"},{"prdName":"iphone","price":3.658,"u.userName":"张三"},{"prdName":"联想笔记本","price":9.32,"u.userName":"李四"}
]

换个写法

products.findAll({attributes: [Sequelize.col('u.userName'),'prdName', 'price'],include: [{model: user,as: 'u',attributes: []}],raw:true
}).then(result => {console.log(JSON.stringify(result))
}).catch(err => {console.log(err)
})

结果3:

[{"userName":"张三","prdName":"ipad","price":4.99},{"userName":"张三","prdName":"iphone","price":3.658},{"userName":"李四","prdName":"联想笔记本","price":9.32}
]

可以看出来结果3是我们想要的结果

加条件的写法:

products.findAll({attributes: [Sequelize.col('u.userName'), 'prdName', 'price'],include: [{model: user,as: 'u',attributes: []}],where: {prdName: 'ipad','$u.userId$': 1},raw: true
}).then(result => {console.log(JSON.stringify(result))
}).catch(err => {console.log(err)
})

对应sql:

SELECT `u`.`userName`, `p`.`prdName`, `p`.`price` FROM `products` AS `p` LEFT OUTER JOIN `user` AS `u` ON `p`.`userId` = `u`.`userId` WHERE `p`.`prdName` = ‘ipad’ AND `u`.`userId` = 1;
如果给include 表加where条件 须使用'$u.userId$'这种写法;也可在include加where条件

事务

function doit() {//启用事务(自动提交)return sequelize.transaction(function (t) {return user.create({userName: '黄晓明',birthDay: '1991-06-23',gender: 0}, {transaction: t}).then(result => {return user.update({userName: '李四',}, {where: { userId: result.userId },transaction: t  //注意(事务transaction 须和where同级)second parameter is "options", so transaction must be in it})})}).then(result => {// Transaction 会自动提交// result 是事务回调中使用promise链中执行结果// console.log(result.length)console.log("ok")}).catch(err => {// Transaction 会自动回滚// err 是事务回调中使用promise链中的异常结果console.log(err)})
}

循环

const Op = Sequelize.Op;
const Promise = require('bluebird');
function recycle() {let tranArray = [];products.findAll({attributes: ['prdId', 'prdName', 'userId', 'price'],raw: true}).then(result => {result.forEach(rec => {tranArray.push(products.create({prdName: rec.prdName,userId: rec.userId,price: rec.price}))})return Promise.all(tranArray)}).then(result => {console.log('result' + result)}).catch(err => {console.log('err' + err)})
}

一般配合事务使用。

Nodejs ORM框架Sequelize相关推荐

  1. Node.js ORM框架-sequelize

    Node.js ORM框架-sequelize 什么是ORM 什么是"持久化" 什么是持久层 ORM技术特点 什么是Sequelize Sequelize特点 使用方式 安装库 配 ...

  2. Node.js ORM 框架 Sequelize 重要更新 v5 发布

    Node.js ORM 框架 Sequelize v5 已正式发布,这也是 v4 推出一年多后的主要版本. Sequelize 是一个基于 promise 的 Node.js ORM,目前支持 Pos ...

  3. nestjs 优秀的ORM框架sequelize操作数据库

    奉上最新代码: nestjs服务demo代码=>gitee地址.github地址 nodejs的ORM–sequelize 笔者在使用koa2开发后端服务的时候用的ORM框架是sequelize ...

  4. php sequelize,egg.js整合数据库ORM框架Sequelize

    在上篇文章中我们写了egg.js怎么连接mysql数据库, 而在一些较为复杂的应用中,我们可能会需要一个 ORM 框架来帮助我们管理数据层的代码.Java中有Mybatis.Hibernate.Spr ...

  5. koa+ts+mysql后台开发——(五)使用orm框架sequelize操作数据库,自定义格式校验、统一处理返回信息、分页格式

    文章目录 前言 一.引包 二.初始化sequelize 三.添加模型层 四.添加服务层 五.添加控制层 (增删改查) 六.自定义数据校验 七.统一处理返回信息 八.统一处理分页格式 九.在路由中引入导 ...

  6. node本地连接服务器的数据库_基于Node.jsORM框架Sequelize的数据库迁移一

    开课吧Web前端教程 前言 在日常的后端项目开发中,我们经常需要和数据库打交道.在这个过程中,我们需要创建数据库.表还有一些测试数据.许多时候,因为业务需求的变更导致的数据库结构的变化,需要修改数据库 ...

  7. Sequelize 4.43.0 发布,基于 Nodejs 的异步 ORM 框架

    Sequelize 4.43.0 发布了,Sequelize 是一款基于 Nodejs 的异步 ORM 框架,它同时支持 PostgreSQL.MySQL.SQLite 和 MSSQL 多种数据库,很 ...

  8. Sequelize 4.42.1 发布,基于 Nodejs 的异步 ORM 框架

    百度智能云 云生态狂欢季 热门云产品1折起>>>   Sequelize 4.42.1 发布了,Sequelize 是一款基于 Nodejs 的异步 ORM 框架,它同时支持 Pos ...

  9. Nodejs相关ORM框架分析

    概述 写这篇blog的原因,想找个node的ORM框架用用,确很难找到一篇对比分析这些ORM框架的文章,唯一找到了一篇,居然是通过star数来论英雄,我觉着很难服众,于是就找几个看看.后来又不想分析, ...

最新文章

  1. 【OpenCV十六新手教程】OpenCV角检测Harris角点检测
  2. VMware下ghost安装XP后无法从硬盘启动的问题
  3. 【ASM 翻译系列第二弹:ASM 12C 版本新特性】
  4. C++动态(显式)调用 C++ dll示例
  5. 实数序列频谱的共轭对称性(DFT与IDFT仿真实现)
  6. Linux中对进程的管理
  7. 新年就是要你红!华为Mate 20 Pro馥蕾红璨星蓝来袭
  8. 【Elasticsearch】es Timelion是Kibana中时间序列的可视化工具
  9. python random_Python random() 函数
  10. mysql主从复制故障处理_MySQL主从复制故障处理一例
  11. python3 md5_Python3.2 --md5
  12. 学习c/c++的50个好网站(转)
  13. Atitit.java的浏览器插件技术 Applet japplet attilax总结
  14. Windows游戏编程 - 简单的弹球窗口
  15. redis持久化(persistent)
  16. android x86 mip,mip-appdl
  17. STM32步进电机S型加减速算法
  18. Graphite简介
  19. windows内存占用过高解决方法
  20. 循环追逐式彩灯电路_应用方案

热门文章

  1. 使用js 调用 google ads
  2. 谈谈Dictionarylt;T1,T2gt;和Listlt;Tgt;的问题 [转]
  3. HTML ajax控件 目录树
  4. php 封装JavaScript类
  5. Linux——alias 设置别名详解
  6. 区块链技术学习之-简单加密货币-高飞币
  7. 【OpenGL】顶点变换常用函数总结
  8. git-管理修改-强化暂存区的意识
  9. dj鲜生-29-登陆后欢迎信息的显示
  10. 索引-linux-技术大钢