Sequelize

sequelize 是一个广泛使用的 ORM 框架,它支持 MySQL、PostgreSQL、SQLite 和 MSSQL 等多个数据源。

安装

$ yarn add egg-sequelize mysql2

配置Sequelize

启用Sequelize

config/plugin.js

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

配置数据源

config/config.${env}.js

exports.sequelize = {
  dialect: 'mysql',
  host: '127.0.0.1',
  port: 3306,
  user: 'root',
  password: 'root',
  database: 'test',
};

定义模型

app/model/article.js

module.exports = app => {
  const { STRING, INTEGER, DATE } = app.Sequelize;
  return app.model.define('article', {
    id: { type: INTEGER, primaryKey: true, autoIncrement: true },
    title: STRING(30),
    content: STRING(255),
    category: STRING(30),
    createdAt: DATE,
    updatedAt: DATE,
  }, {
    freezeTableName: true, // 表格名字不轉化為複數
    underscored: false, // 不自動轉化為下劃線
  });
};

这个 Model 就可以在 Controller 和 Service 中通过 app.model.Article 或者 ctx.model.Article 访问到了

例如我们在控制器中使用

app/controller/article.js

'use strict';
const Controller = require('egg').Controller;
function toInt(str) {
  if (typeof str === 'number') return str;
  if (!str) return str;
  return parseInt(str, 10) || 0;
}
module.exports = class extends Controller {
  async index() {
    const { ctx } = this;
    const query = { limit: toInt(ctx.query.limit), offset: toInt(ctx.query.offset) };
    ctx.body = await ctx.model.Article.findAll(query);
  }
  async show() {
    const ctx = this.ctx;
    ctx.body = await ctx.model.Article.findByPk(toInt(ctx.params.id));
  }
  async create() {
    const ctx = this.ctx;
    const { title, content, category } = ctx.request.body;
    const article = await ctx.model.Article.create({ title, content, category });
    ctx.status = 201;
    ctx.body = article;
  }
  async update() {
    const ctx = this.ctx;
    const id = toInt(ctx.params.id);
    const article = await ctx.model.Article.findByPk(id);
    if (!article) {
      ctx.status = 404;
      return;
    }
    const { title, content, category } = ctx.request.body;
    await article.update({ title, content, category });
    ctx.body = article;
  }
  async destroy() {
    const ctx = this.ctx;
    const id = toInt(ctx.params.id);
    const article = await ctx.model.Article.findByPk(id);
    if (!article) {
      ctx.status = 404;
      return;
    }
    await article.destroy();
    ctx.status = 200;
  }
};

创建资源路由:

'use strict';
module.exports = ({ router, controller }) => {
  router.resources('article', '/article', controller.article);
};

在浏览器中输入以下地址进行测试:

  • http://127.0.0.1:7001/article
  • http://127.0.0.1:7001/article/1
  • http://127.0.0.1:7001/article?limit=2&offset=2

其他接口通过Postman测试正常

更多有关Sequelize的介绍参考我编写的另一本书:

Sequelize

MIT Licensed | Copyright © 2018-present 滇ICP备16006294号

Design by Quanzaiyu | Power by VuePress