Sticky Note | 易用的 Node SQL ORM —— Sequelize 简单使用 (CURD)

754 阅读2分钟

Sequelize 中文文档 www.sequelize.com.cn/core-concep…

Sequelize Github github.com/sequelize/s…

Mysql2 Github github.com/sidorares/n…

本文代码地址 github.com/LuckyChou71…

本文环境

    "mysql2": "^2.3.3",
    "sequelize": "^6.17.0"

表结构

+---------------+--------------+------+-----+---------+----------------+
| Field         | Type         | Null | Key | Default | Extra          |
+---------------+--------------+------+-----+---------+----------------+
| user_id       | int          | NO   | PRI | NULL    | auto_increment |
| user_nickname | varchar(255) | NO   |     | NULL    |                |
| user_password | varchar(255) | NO   |     | NULL    |                |
| user_role     | int          | YES  |     | 0       |                |
| createdAt     | datetime     | NO   |     | NULL    |                |
| updatedAt     | datetime     | NO   |     | NULL    |                |
+---------------+--------------+------+-----+---------+----------------+

Mysql2

首页我们用 Mysql2 来实现 CURD (增删改查)

  1. 安装 mysql2
yarn add mysql2
  1. 连接数据库
const mysql = require('mysql2');

// 创建一个默认配置的连接池
const pool = mysql.createPool({
  host: 'localhost',
  user: 'root', // 数据库用户名
  password: 'xxxxx', // 数据库密码
  database: 'test', // 用哪个数据库 这里我用的是test数据库
  charset: 'utf8', //应该设置编码(省略在某些情况下会有错误)

  //以下选项均为默认值(如果不需要变动可省略)
  acquireTimeout: 10000, //获取连接的毫秒
  waitForConnections: true, //为true时,连接排队等待可用连接。为false将立即抛出错误
  connectionLimit: 10, //单次可创建最大连接数
  queueLimit: 0, //连接池的最大请求数,从getConnection方法前依次排队。设置为0将没有限制
});

module.exports = pool;
  1. 编写sql语句
const pool = require('./connect');

// 增
pool.query(
  `insert into user_info (user_nickname, user_password, user_role) values ('nanshu', '710', 0)`,
  (err, result) => {
    console.log(result);
  }
);

// 删
pool.query(
  `delete from user_info where user_nickname = chou;`,
  (err, result) => {
    console.log(result);
  }
);

// 改
pool.query(
  `update user_info set user_nickname = 'nanshu' where user_nickname = 'chou'; `,
  (err, result) => {
    console.log(result);
  }
);

// 查
pool.query('select * from user_info', (err, result) => {
  console.log(result);
});

可以看到 使用了 mysql2 这个库后 项目中需要编写大量的sql语句 这会让项目变得复杂且不易维护

Sequelize

安装 Sequelize

yarn add sequelize
  1. 连接数据库
const { Sequelize } = require('sequelize');

// 连接
const sequelize = new Sequelize('test', 'root', 'szrk0209', {
  host: 'localhost',
  dialect: 'mysql',
});

// 测试连接
try {
  await sequelize.authenticate();
  console.log('Connection has been established successfully.');
} catch (error) {
  console.error('Unable to connect to the database:', error);
}
  1. 创建模型
const { Sequelize, DataTypes } = require('sequelize');
const sequelize = new Sequelize('test', 'root', 'szrk0209', {
  host: 'localhost',
  dialect: 'mysql',
});

const UserInfo = sequelize.define(
  'user_info',
  {
    // 在这里定义模型属性
    user_id: {
      type: DataTypes.INTEGER,
      autoIncrement: true,
      primaryKey: true,
    },
    user_nickname: {
      type: DataTypes.STRING,
      allowNull: false,
    },
    user_password: {
      type: DataTypes.STRING,
      allowNull: false,
    },
    user_role: {
      type: DataTypes.INTEGER,
      defaultValue: 0,
    },
  },
  {
    // 这是其他模型参数
  }
);

// `sequelize.define` 会返回模型
console.log(UserInfo === sequelize.models.UserInfo); // true
  1. 同步模型
/**
 * sync() - 如果表不存在,则创建该表(如果已经存在,则不执行任何操作)
 * sync({ force: true }) - 将创建表,如果表已经存在,则将其首先删除
 * sync({ alter: true }) - 这将检查数据库中表的当前状态(它具有哪些列,它们的数据类型等),然后在表中进行必要的更改以使其与模型匹配.
 *
 * 可以使用 sequelize.sync() 自动同步所有模型
 */
await UserInfo.sync();
  1. 操作模型
  // 增
  await UserInfo.create({
    user_nickname: 'chou',
    user_password: '209',
  });

  // 删
  await UserInfo.destroy({
    where: {
      user_nickname: 'chou',
    },
  });

  // 改
  await UserInfo.update(
    {
      user_role: 1,
    },
    {
      where: {
        user_id: 0,
      },
    }
  );

  // 查
  await UserInfo.findAll();
  // SELECT
  // 只筛选某些属性
  await UserInfo.findAll({
    attributes: ['user_nickname'],
  });
  // 排除某些属性
  await UserInfo.findAll({
    attributes: {
      exclude: ['user_role'],
    },
  });

  // WHERE
  // 没有指定Op 默认是 eq
  await UserInfo.findAll({
    where: {
      user_nickname: 'chou',
    },
  });
  // 等价于
  await UserInfo.findAll({
    where: {
      user_nickname: {
        [Op.eq]: 'chou',
      },
    },
  });
  // 多个查询条件时 Op 默认是 and
  await UserInfo.findAll({
    where: {
      user_nickname: 'chou',
      user_role: 0,
    },
  });
  // 等价于
  await UserInfo.findAll({
    where: {
      [Op.and]: {
        user_nickname: 'chou',
        user_role: 0,
      },
    },
  });
  // 使用 or
  await UserInfo.findAll({
    where: {
      [Op.or]: {
        user_nickname: 'chou',
        user_role: 0,
      },
    },
  });

  /**
   * Op
   * @link https://www.sequelize.com.cn/core-concepts/model-querying-basics#%E6%93%8D%E4%BD%9C%E7%AC%A6
   */

  // 排序
  await UserInfo.findAll({
    order: [['user_id', 'DESC']],
  });
  await UserInfo.findAll({
    order: sequelize.literal('max(user_id) DESC'),
  });

  // 限制和分页
  await UserInfo.findAll({
    limit: 10,
  });
  await UserInfo.findAll({
    offset: 10,
  });
  await UserInfo.findAll({
    offset: 10,
    limit: 10,
  });

可以看到 使用了 ORM 模型后 sql不仅变得易操作 且易于维护