在node开发中,通常使用ORM框架来简化直接操作数据库,Sequelize是当前很流行的ORM框架,本系列文章就来记录一下:笔者在学习和使用Sequelize的平坦又坎坷的历程
Sequelize增删改查函数
SQL | 函数 |
---|---|
select | findAll、findOne、findByPk、findAndCountAll |
update | update |
insert | create |
update | delete |
查询
查询单条数据
const user = await ctx.model.User.findOne({
attributes: ['id', 'name'], // 结果过滤,只显示 id,name 字段
// attributes: { exclude: ['role'] } // 不显示 role 字段
where: {
id: id
},
order: [ // 排序
['showCount', 'DESC']
]
});
// 字段重命名:查询属性(字段)可以通过传入一个嵌套数据进行重命名
attributes: ['id', ['name', 'myName']]
// 将字段name重命名为myName,这样返回的结果里面的字段就是myName
查询多条数据
const user = await ctx.model.User.findAll({
limit: 10, //每页10条
offset: 0 * 10, //第x页*每页个数
where: {} // 条件
});
分页查询
// 返回列表的总数
const { app, ctx } = this;
const { gt } = app.Sequelize.Op;
const user = await ctx.model.User.findAndCountAll({
limit: 10, //每页10条
offset: 0 * 10, //第x页*每页个数
where: { // 条件
id: {
[gt]: 6 // id > 6
}
}
});
通过id查询
const user = await ctx.model.User.findByPk(1);
查询单个数据
const user = await ctx.model.User.findOne({
where: {} // 条件
});
分组查询
分组查询一般要和聚合函数一起使用,聚合函数如下
聚合函数 | 功能 |
---|---|
COUNT | 用于统计记录条数 |
SUM | 用于计算字段的值的总和 |
AVG | 用于计算字段的值的平均值 |
MAX | 用于查找查询字段的最大值 |
MIN | 用于查找查询字段的最小值 |
// 求表中num字段值的和
const { app, ctx } = this;
const { fn, col } = app.Sequelize;
// fn 指的是函数
// col 指的是字段
const user = await ctx.model.User.findOne({
attributes: [[fn('SUM', col('num')), 'all_num']],
where: {} // 条件
});
// sql语句:select sum('num') as 'all_count' ...
新增
// 如果id为自增的主键,那么新增数据时候不需要添加id
const user = await ctx.model.User.create({ name, age });
修改
// 修改之前先判断这条数据是否存在
const user = await ctx.model.User.findByPk(id);
// 如果数据存在,再修改
await user.update({ name, age }, {
where: {}
});
删除
// 删除之前先判断这条数据是否存在
const user = await ctx.model.User.findByPk(id);
// 如果数据存在,再修改
await user.destroy();
下期预告,记录一下关联查询的方法。
记录记录!