文档:

Sequelize基础查询:https://github.com/demopark/sequelize-docs-Zh-CN/blob/master/core-concepts/model-querying-basics.md
Sequelize查询api:https://github.com/demopark/sequelize-docs-Zh-CN/blob/master/core-concepts/model-querying-finders.md
Sequelize关联查询:https://github.com/demopark/sequelize-docs-Zh-CN/blob/master/advanced-association-concepts/eager-loading.md#eager-loading—-%E9%A2%84%E5%85%88%E5%8A%A0%E8%BD%BD

基础查询

查询整张表

  1. SELECT * FROM ...
  1. const Admin = require('../models/Admin');
  2. /**
  3. * 查询所有管理员
  4. * @returns
  5. */
  6. exports.getAdmins = async function() {
  7. const res = await Admin.findAll() // 等同于 SELECT * FROM ...
  8. // 将返回来的嵌套对象拍平,然后在转化为正常对象
  9. return JSON.parse(JSON.stringify(res))
  10. }

SELECT 查询特定属性

可以查看顶部文档

where 查询

检测账号密码登录

  1. const Admin = require('../models/Admin');
  2. /**
  3. * 登录
  4. * 并没有对密码就行md5加密 以及返回的数据不能包含密码
  5. * @param {*} loginId
  6. * @param {*} loginPwd
  7. * @returns
  8. */
  9. exports.login = async function (loginId, loginPwd) {
  10. const res = await Admin.findOne({
  11. where: {
  12. loginId,
  13. loginPwd,
  14. },
  15. }); //等效于 SELECT * FROM admin WHERE loginId = loginId AND loginPwd = loginPwd
  16. /**mysql 不区分大小写 */
  17. if (res && loginId === res.loginId && loginPwd === res.loginPwd) {
  18. return res.toJSON();
  19. } else {
  20. return null;
  21. }
  22. };

对密码进行加密且控制返回值

  1. const Admin = require('../models/Admin');
  2. const md5 = require("md5");
  3. exports.login = async function (loginId, loginPwd) {
  4. loginPwd = md5(loginPwd)
  5. const result = await Admin.findOne({
  6. where: {
  7. loginId,
  8. loginPwd,
  9. },
  10. });
  11. if (result && result.loginId === loginId) {
  12. const {id ,loginId} = res.toJSON();
  13. return {
  14. id,
  15. loginId
  16. }
  17. }
  18. return null;
  19. };

运算符

东西太多且零碎
文档地址:https://github.com/demopark/sequelize-docs-Zh-CN/blob/master/core-concepts/model-querying-basics.md

分页查询

使用 limitoffset 参数可以进行 限制/分页:

  1. // 提取10个实例/行
  2. Project.findAll({ limit: 10 });
  3. // 跳过8个实例/行
  4. Project.findAll({ offset: 8 });
  5. // 跳过5个实例,然后获取5个实例
  6. Project.findAll({ offset: 5, limit: 5 });

联表查询

单个关联元素

  1. exports.getStuall = async function() {
  2. const res = await Student.findAll({
  3. // attributes: ['id', 'name', 'sex', 'birthdady'],
  4. include: [Class],
  5. });
  6. return JSON.parse(JSON.stringify(res));
  7. }
  8. require('./models/relation'); // 必须有这个声明关系 不然查不到
  9. const stuServ = require('./services/studentService');
  10. stuServ.getStuall().then(res => {
  11. console.log(res)
  12. })

输出

  1. Executing (default): SELECT `Student`.`id`, `Student`.`name`, `Student`.`birthdady`, `Student`.`sex`, `Student`.`mobile`, `Student`.`deletedAt`, `Student`.`ClassId`, `Class`.`id` AS `Class.id`, `Class`.`name` AS `Class.name`, `Class`.`openDate` AS `Class.openDate`, `Class`.`deletedAt` AS `Class.deletedAt` FROM `Students` AS `Student` LEFT OUTER JOIN `Classes` AS `Class` ON `Student`.`ClassId` = `Class`.`id` AND (`Class`.`deletedAt` IS NULL) WHERE (`Student`.`deletedAt` IS NULL);
  2. [
  3. {
  4. id: 1,
  5. name: '何杰',
  6. birthdady: '1988-05-24',
  7. sex: false,
  8. mobile: '13773242951',
  9. deletedAt: null,
  10. ClassId: 3,
  11. Class: {
  12. id: 3,
  13. name: '挖掘机炒菜 3 班',
  14. openDate: '2017-04-18',
  15. deletedAt: null
  16. }
  17. },
  18. {
  19. id: 2,
  20. name: '白秀英',
  21. birthdady: '1995-12-30',
  22. sex: true,
  23. mobile: '13821143636',
  24. deletedAt: null,
  25. ClassId: 10,
  26. Class: {
  27. id: 10,
  28. name: '挖掘机炒菜 10 班',
  29. openDate: '2010-04-24',
  30. deletedAt: null
  31. }
  32. },
  33. {
  34. id: 3,
  35. name: '任敏',
  36. birthdady: '2002-12-24',
  37. sex: false,
  38. mobile: '13535837226',
  39. deletedAt: null,
  40. ClassId: 14,
  41. Class: {
  42. id: 14,
  43. name: '挖掘机炒菜 14 班',
  44. openDate: '2002-02-20',
  45. deletedAt: null
  46. }
  47. },
  48. {
  49. id: 4,
  50. name: '孔娜',
  51. birthdady: '1999-10-04',
  52. sex: false,
  53. mobile: '13729124141',
  54. deletedAt: null,
  55. ClassId: 14,
  56. Class: {
  57. id: 14,
  58. name: '挖掘机炒菜 14 班',
  59. openDate: '2002-02-20',
  60. deletedAt: null
  61. }
  62. },
  63. {
  64. id: 5,
  65. name: '邵娜',
  66. birthdady: '1986-08-19',
  67. sex: false,
  68. mobile: '13534267583',
  69. deletedAt: null,
  70. ClassId: 7,
  71. Class: {
  72. id: 7,
  73. name: '挖掘机炒菜 7 班',
  74. openDate: '1971-09-27',
  75. deletedAt: null
  76. }
  77. }
  78. ]

复杂查询示例

  1. const Book = require("../models/Book");
  2. const { Op } = require("sequelize");
  3. /**
  4. * 模糊查询书名或者作者名,且分页
  5. * @param {*} page
  6. * @param {*} limit
  7. * @param {*} keywords
  8. * @returns
  9. */
  10. exports.getBooks = async function (page = 1, limit = 10, keywords = "") {
  11. const result = await Student.findAndCountAll({
  12. attributes: ["id", "name", "sex", "birthdady"],
  13. where: {
  14. [Op.or]: [
  15. //里面的两个条件是或者关系
  16. {
  17. //条件1:姓名模糊匹配关键词
  18. name: {
  19. [Op.like]: `%${keywords}%`,
  20. },
  21. },
  22. {
  23. //条件2:作者模糊匹配关键词
  24. author: {
  25. [Op.like]: `%${keywords}%`,
  26. },
  27. },
  28. ],
  29. },
  30. offset: (page - 1) * limit,
  31. limit: +limit,
  32. });
  33. return {
  34. total: result.count,
  35. datas: JSON.parse(JSON.stringify(result.rows)),
  36. };
  37. };
  1. const Student = require("../models/Student");
  2. const { Op } = require("sequelize");
  3. const Class = require("../models/Class");
  4. /**
  5. * 查询符合条件的学生,且附带班级信息
  6. */
  7. exports.getStudents = async function (
  8. page = 1,
  9. limit = 10,
  10. sex = -1,
  11. name = ""
  12. ) {
  13. const where = {};
  14. if (sex !== -1) {
  15. where.sex = !!sex;
  16. }
  17. if (name) {
  18. where.name = {
  19. [Op.like]: `%${name}%`,
  20. };
  21. }
  22. /**
  23. * 分页查询学生的部分信息
  24. */
  25. const result = await Student.findAndCountAll({
  26. attributes: ["id", "name", "sex", "birthdady"],
  27. where,
  28. include: [Class], // 联表查询
  29. offset: (page - 1) * limit,
  30. limit: +limit,
  31. });
  32. return {
  33. total: result.count,
  34. datas: JSON.parse(JSON.stringify(result.rows)),
  35. };
  36. };

只查询主键

findByPk 方法使用提供的主键从表中仅获得一个条目.

  1. /**
  2. * 通过主键查询管理员
  3. * @param {*} id
  4. * @returns
  5. */
  6. exports.getAdminById = async function (id) {
  7. const result = await Admin.findByPk(id);
  8. if (result) {
  9. return result.toJSON();
  10. }
  11. return null;
  12. };

只查询一条数据

findOne 方法获得它找到的第一个条目(它可以满足提供的可选查询参数).
示例看上面where查询的示例