Egg使用Sequelize查询数据 —— WHERE中使用的操作符符号

919 阅读1分钟

其他文章:
文章一:Node框架之Egg —— EggJS+MySQL(mysql2+egg-sequelize+egg-cors)实现简单的增删改查
文章二:Node框架之Egg的中间件 —— 登录鉴权

一. 简介

Sequelize 是一个基于 Promise 的 Node.js ORM,适用于 Postgres、MySQL、MariaDB、SQLite 和 Microsoft SQL Server。它具有可靠的事务支持、关系、急切和延迟加载、读取复制等。

在MySQL中,
最基本的查询。 查询所有文章: SELECT * FROM article
组合WHERE句子。 查询查看次数在50到100之间的文章: SELECT * FROM article WHERE view BETWEEN 50 AND 100;
LIKE子句。 查询文章标题中包含“Vue”的文章:SELECT * FROM article WHERE title LIKE "%Vue%"

以上是SQL语句的写法,换做是Sequelize该怎么去实现呢?

二. Sequelize使用操作符

在使用之前,确保你的Egg项目已经安装了sequelize。文章一 中已经有Sequelize的基本使用。
Sequelize 提供了多种运算符: image.png

1. 配置

// config/config.default.js

'use strict';
const Op = require('sequelize').Op;
module.exports = appInfo => {
  ...
  /* 连接mysql配置 */
  config.sequelize = {
    dialect: 'mysql',
    host: 'localhost',
    port: 3306,
    database: 'blog',
    username: 'root',
    password: '123456',
    operatorsAliases: {
      $eq: Op.eq,
      $ne: Op.ne,
      $gte: Op.gte,
      $gt: Op.gt,
      $lte: Op.lte,
      $lt: Op.lt,
      $not: Op.not,
      $in: Op.in,
      $notIn: Op.notIn,
      $is: Op.is,
      $like: Op.like,
      $notLike: Op.notLike,
      $iLike: Op.iLike,
      $notILike: Op.notILike,
      $regexp: Op.regexp,
      $notRegexp: Op.notRegexp,
      $iRegexp: Op.iRegexp,
      $notIRegexp: Op.notIRegexp,
      $between: Op.between,
      $notBetween: Op.notBetween,
      $overlap: Op.overlap,
      $contains: Op.contains,
      $contained: Op.contained,
      $adjacent: Op.adjacent,
      $strictLeft: Op.strictLeft,
      $strictRight: Op.strictRight,
      $noExtendRight: Op.noExtendRight,
      $noExtendLeft: Op.noExtendLeft,
      $and: Op.and,
      $or: Op.or,
      $any: Op.any,
      $all: Op.all,
      $values: Op.values,
      $col: Op.col,
    },
  };

  return {
    ...config
  };
};

2. 查询数据

// server/base.js

'use strict';
const Service = require('egg').Service;
class BaseService extends Service {
    async findAll(modelName){
        const option = {
            where:{
              title: {
                $like: `%Vue%`, // 模糊查询:查询文章标题中包含“Vue”的文章
              },
              view: {
                $between: [50, 100], // 查询查看次数在50到100之间的文章
              },
            }
        }
        const { count, rows } = await ctx.model[modelName].findAndCountAll(option);
        return { count, rows };
    }
}

好了,其实WHERE中使用的操作符符号的使用还是挺简单的,暂时举例这两个吧!


fx.jpg