findAll/One/Pk(sequelize)
findAll
-
findAll查询所有实例-
查出全表
const dataAll = await this.ctx.model.Book.findAll() -
查出全表的部分列
const dataAll = await this.ctx.model.Book.findAll({ attributes: ['title','author'] //或者用排除法 //attributes: { exclude: ['content'] } })
-
-
findAll+where条件查询所有满足实例-
查一条
this.ctx.model.Book.findAll({ where:{ id: 1 } }) -
查
ANDthis.ctx.model.Book.findAll({ where:{ id: 1 status:‘active’ } })- 等价于
const { Op } = require("sequelize"); this.ctx.model.Book.findAll({ where:{ [Op.and]:[ {id: 1} {status:‘active’} ] } })
- 等价于
-
查
Orconst { Op } = require("sequelize"); this.ctx.model.Book.findAll({ where:{ [Op.or]:[ {id: 1} {status:‘active’} ] } }) -
查
Inconst { Op } = require("sequelize"); this.ctx.model.Book.findAll({ where:{ id: [1,2,3] } }) -
还有很多很多Op下面的操作符,不一一列举
-
-
findAll+sequelize对象的方法查询所有实例-
第一步
.col(列名),- 可得到某一列,作为下面的第二参数
-
第二步
.fn(‘函数名’,某一列)- 可得到某一规则,作为下面的第一参数
-
第三步: 配合order排序使用:
.findAll({ order:[ [sequelize.fn('max', sequelize.col('age')), 'DESC'], //按最大年龄进行降序排序 ] }) -
还有group分组排列使用:
.findAll({ group: 'name' }); -
还有limit限制+offset分页使用:
.findAll({ offset: 5, limit: 5 }); //跳过前面5个实例,从第六个开始取5个实例
-
findOne
findOne查询第一条满足实例this.ctx.model.Book.findOne({ where:{ title:'fengmk2' } })
findByPk
findByPk查询满足主键为某值的实例this.ctx.model.Book.findByPk(123);