egg.js整合數(shù)據(jù)庫ORM框架Sequelize

在上篇文章中我們寫了egg.js怎么連接mysql數(shù)據(jù)庫, 而在一些較為復雜的應用中,我們可能會需要一個 ORM 框架來幫助我們管理數(shù)據(jù)層的代碼。Java中有Mybatis、Hibernate、Spring Data Jpa, 在Php中Thinkphp框架也集成ORM框架功能, 而在 Node.js 中,sequelize 是一個我們廣泛使用的 ORM 框架,它支持 MySQL、PostgreSQL、SQLite 和 MSSQL 等多個數(shù)據(jù)源

安裝
cnpm i -S egg-sequelize mysql2
開啟sequelize插件

config/plugin.js

module.exports = {
  sequelize: {
    enable: true,
    package: 'egg-sequelize',
  }
};
配置sequelize

我們這里連接mysql數(shù)據(jù)庫

/* eslint valid-jsdoc: "off" */

'use strict';

/**
 * @param {Egg.EggAppInfo} appInfo app info
 */
module.exports = appInfo => {
  /**
   * built-in config
   * @type {Egg.EggAppConfig}
   **/
  const config = exports = {
    // sequelize配置
    sequelize: {
      dialect: 'mysql',
      host: 'ip地址',
      port: 3306,
      database: 'test',
      username: 'root',
      password: '123456'
    }
  };

  // use for cookie sign key, should change to your own and keep security
  config.keys = appInfo.name + '_1565058424941_6691';

  // add your middleware config here
  config.middleware = [];

  // add your user config here
  const userConfig = {
    // myAppName: 'egg',
  };

  return {
    ...config,
    ...userConfig,
  };
};
數(shù)據(jù)庫遷移(Migrations)

在實際開發(fā)中, 大部分情況下是多人協(xié)作的, 在項目的演進過程中, 每一次迭代都可能對數(shù)據(jù)庫結(jié)構(gòu)做變更, 怎么解決這個問題? 這時候我們就需要Migrations來幫我們管理數(shù)據(jù)結(jié)構(gòu)的變更了
sequelize提供了sequelize-cli工具來實現(xiàn)Migrations

  • 先安裝sequelize-cli
cnpm i --save-dev sequelize-cli
  • 在根目錄創(chuàng)建.sequelizerc文件
'use strict';
const path = require('path');
module.exports = {
  config: path.join(__dirname, 'database/config.json'),
  'migrations-path': path.join(__dirname, 'database/migrations'),
  'seeders-path': path.join(__dirname, 'database/seeders'),
  'models-path': path.join(__dirname, 'app/model'),
};
  • 初始化 Migrations 配置文件和目錄
// 執(zhí)行下面兩條命令, 會根據(jù)根目錄下我們剛才創(chuàng)建的.sequelizerc生成Migrations 配置文件和目錄
npx sequelize init:config
npx sequelize init:migrations

執(zhí)行完上面兩條命令, 根目錄多了個database文件夾

database
├── migrations
└── config.json

到這里, sequelize-cli和相關配置都初始化好了

創(chuàng)建表

在 Migration 文件來創(chuàng)建我們的表users
執(zhí)行下面的命令

npx sequelize migration:generate --name=init-users

執(zhí)行完后會在 database/migrations 目錄下生成一個 migration 文件(${timestamp}-init-users.js),我們修改它來處理初始化 users 表
我這里生成的是20190806050532-init-users.js, 修改該文件內(nèi)容

'use strict';

module.exports = {
  // 在執(zhí)行數(shù)據(jù)庫升級時調(diào)用的函數(shù),創(chuàng)建 users 表
  up: async (queryInterface, Sequelize) => {
    const { INTEGER, DATE, STRING } = Sequelize;
    await queryInterface.createTable('users', {
      id: { type: INTEGER, primaryKey: true, autoIncrement: true },
      name: STRING(30),
      age: INTEGER,
      created_at: DATE,
      updated_at: DATE,
    });
  },
  // 在執(zhí)行數(shù)據(jù)庫降級時調(diào)用的函數(shù),刪除 users 表
  down: async queryInterface => {
    await queryInterface.dropTable('users');
  },
};

執(zhí)行 migrate 進行數(shù)據(jù)庫變更

# 升級數(shù)據(jù)庫
npx sequelize db:migrate
# 如果有問題需要回滾,可以通過 `db:migrate:undo` 回退一個變更
# npx sequelize db:migrate:undo
# 可以通過 `db:migrate:undo:all` 回退到初始狀態(tài)
# npx sequelize db:migrate:undo:all

執(zhí)行npx sequelize db:migrate之后, 我們現(xiàn)在去查看數(shù)據(jù)庫多兩張表SequelizeMeta和users

接下來我們就可以編寫代碼進行數(shù)據(jù)庫操作了

創(chuàng)建app/model/user.js

'use strict';

module.exports = app => {
  const { STRING, INTEGER, DATE } = app.Sequelize;

  const User = app.model.define('users', {
    id: { type: INTEGER, primaryKey: true, autoIncrement: true },
    name: STRING(30),
    age: INTEGER,
    created_at: DATE,
    updated_at: DATE,
  });

  return User;
};

這里創(chuàng)建的Model模型可以在Controller和Service中通過app.model.User或ctx.model.User訪問
我們創(chuàng)建一個app/controller/user.js

const Controller = require('egg').Controller;
class UserController extends Controller {
  async index() {
    // 查詢所有用戶信息
    ctx.body = await this.ctx.model.User.findAll();
  }
}
module.exports = UserController;
最后一步配置路由

app/router.js

module.exports = app => {
  const { router, controller } = app;
  router.get('/user', controller.user.index);
};
測試

訪問: http://localhost7001/user

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務。

相關閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容