1.建立连接

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, updateAt
timestamps: false,
//可以给表设置别名
freezeTableName: true,
// 字段以下划线(_)来分割(默认是驼峰命名风格)
underscored: false
},
//sequelize v4 必须设置方言
dialect: 'mysql',
//默认DECIMAL and NEWDECIMAL 返回 String
dialectOptions: {
decimalNumbers: true
},
//设置别名,否则不识别$like等关键词($like: Op.like对应关系)
operatorsAliases: 'object',
//时间上的统一
timezone: "+08:00",
})

2.模型定义

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,否则需要。

3.查询数据

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条件

4.事务

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)
})
}

5. 循环

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. Nodejs ORM框架Sequelize快速入门

    Nodejs ORM框架Sequelize快速入门 什么是ORM? 简单的讲就是对SQL查询语句的封装,让我们可以用OOP的方式操作数据库,优雅的生成安全.可维护的SQL代码.直观上,是一种Model ...

  2. Node.js ORM 框架 sequelize 实践

    最近在做团队的一个内部系统,这次使用的nodejs web框架是团队统一的hapi.js,而数据库依然是mysql,ORM 框架选用有着6000+ stars 的 sequelize.js,hapi- ...

  3. 【前端】nodejs的ORM框架sequelize的工厂化

    转载请注明出处:http://www.cnblogs.com/shamoyuu/p/sequelize_factory.html 一.什么是sequelize nodejs的后台在操作数据库的时候,需 ...

  4. Node.js ORM框架Sequelize使用示例

    示例代码: const Sequelize = require('sequelize'); const sequelize = new Sequelize('database', 'username' ...

  5. Django框架之数据库ORM框架

    首先,我来介绍一下什么是ORM框架: O是object,也就类对象的意思,R是relation,翻译成中文是关系,也就是关系数据库中数据表的意思,M是mapping,是映射的意思.在ORM框架中,它帮 ...

  6. Node.js ORM框架Sequlize之表间关系

    Sequelize模型之间存在关联关系,这些关系代表了数据库中对应表之间的主/外键关系.基于模型关系可以实现关联表之间的连接查询.更新.删除等操作.本文将通过一个示例,介绍模型的定义,创建模型关联关系 ...

  7. Django(三) 模型:ORM框架、定义模型类并创建一个对应的数据库、配置Mysql数据库

    一.模型概述 https://docs.djangoproject.com/zh-hans/3.0/intro/tutorial02/ https://www.runoob.com/django/dj ...

  8. Rafy 领域实体框架 - 树型实体功能(自关联表)

      在 Rafy 领域实体框架中,对自关联的实体结构做了特殊的处理,下面对这一功能进行讲解. 场景 在开发数据库应用程序时,往往会遇到自关联表的场景.例如,分类信息.组织架构中的部门.文件夹信息等,都 ...

  9. Spring事务管理--多个ORM框架在使用时的情况分析

    公司的项目已经接近尾声了,总结一下项目中用到的技术,我发现项目中的有些东西还是挺模糊的,只是知道这么用就行了.并不清楚其中的原理.由于公司的项目比较老,是7年前的一个项目了,中间一直有人在维护,也是在 ...

随机推荐

  1. Java基础周测一、二(50题)

    一.单选题 (共50题,250分) 1.下列选项不可作为Java语言变量名的是(    ). A. a1 B. $1 C. _1 D. 21 正确答案: D 2.有一段Java应用程序,它的类名是a1 ...

  2. Java初学者作业——编写Java程序,输入一个学生的5门课程的成绩,求其平均分。

    返回本章节 返回作业目录 需求说明: 编写Java程序,输入一个学生的5门课程的成绩,求其平均分.计算平均成绩,需要将每一门课程的成绩逐步累加到总成绩中,使用 for 循环实现,然后求出平均分. 实现 ...

  3. JMeter_使用正则和JSON提取器参数化(常用于提取token)

    一.使用正则表达式提取器提取token 查看登录响应参数找出token.图中token为 "ticketString": "ccf26b17-a96f-4913-8925 ...

  4. 原生android webview 显示的H5页面颜色属性无法识别 - 具体解决心得

    1.前言 background-color: #fc1717bf; 这个样式属性没毛病吧,浏览器都是支持的,但是在android 7.0 系统无法正确识别这个含有透明度的属性, 即bf无法识别,将默认 ...

  5. spring security 自动登录 --- 心得

    1.前言 仍然是使用cookie存储登录数据,但是存储的数据 由 spring security自动创建 ,当登出后自动删除cookie, 如果不登出也仍在生命周期内,关闭浏览器再打开将会自动登录,无 ...

  6. 老旧业务重构案例——IM系统如何设计

    一年半之前刚来到这个团队,便遭遇了一次挑战: 当时有个CRM系统,老是出问题,之前大的优化进行了4次小的优化进行了10多次,要么BUG重复出现,要么性能十分拉胯,总之体验是否糟糕!技术团队因此受到了诸 ...

  7. LG1290 欧几里德的游戏

    https://www.luogu.com.cn/problem/P1290 博弈论游戏,用到mod. 辗转相除法的过程,会构成n种状态. 到达最后一个状态就赢了. 对于一次过程如果div>1那 ...

  8. 灵雀云入选Gartner 2020中国ICT技术成熟度曲线报告,容器技术处于顶峰

    近日,全球权威咨询分析机构Gartner发布了"2020中国ICT技术成熟度曲线(Hype Cycle for ICT in China, 2020 )"报告,灵雀云作为国内容器和 ...

  9. 使用Spring容器动态注册和获取Bean

    有时候需要在运行时动态注册Bean到Spring容器,并根据名称获取注册的Bean.比如我们自己的SAAS架构的系统需要调用ThingsBoard API和Thingsboard交互,就可以通过Thi ...

  10. CMake与OpenMP

    CMake与OpenMP cmake_minimum_required (VERSION 2.6) project (TEST) set (TEST_VERSION 0.1) set(CMAKE_BU ...