egg+sequelize+mysql實現CRUD操作


開發環境

  • node v10.16.3
  • mysql v8.0.18 

第一步:確保能夠跑起來

  • mkdir egg-test && cd egg-test
  • npm init egg --type=simple
  • npm install
  • npm run dev
  • 結果

    image.png

第二步:完成CRUD功能

  • mysql准備
    • mysql用戶名,密碼和數據庫名
      • user:root
      • password:123456
      • database:test
    • test->user表結構
      •  

         

  • 安裝依賴包
    • npm install --save egg-sequelize mysql2
  • 目錄結構

      image.png 

  • config/plugin.js

 

'use strict';

/** @type Egg.EggPlugin */
module.exports = {
  sequelize: {
    enable: true,
    package: 'egg-sequelize',
  },
};

 

  • config/config.default.js:數據庫的配置

 

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

'use strict';

/**
 * @param {Egg.EggAppInfo} appInfo app info
 */
module.exports = appInfo => {
  /**
   * built-in config
   * @type {Egg.EggAppConfig}
   **/
  const config = exports = {};

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

  // add your middleware config here
  config.middleware = [];
  config.security = {
    csrf: false,
    ctoken: false,
  };
  config.sequelize = {
    dialect: 'mysql',
    host: '127.0.0.1',
    port: '3306',
    user: 'root',//用戶名
    password: '123456',//用戶密碼
    database: 'test',//數據庫名
    define: {
      underscored: true,
      freezeTableName: true,
    },
  };
  // add your user config here
  const userConfig = {
    // myAppName: 'egg',
  };

  return {
    ...config,
    ...userConfig,
  };
}; 

 

  • model/user.js

 

'use strict';
module.exports = app => {
  const { STRING, INTEGER } = app.Sequelize;
  const User = app.model.define('user', {
    id: { type: INTEGER, primaryKey: true, autoIncrement: true },
    nickname: STRING(20),
  }, {
    timestamps: false,
  });
  return User;
};

 

  • controller/user.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;
}
class UserController extends Controller {
  async index() {
    const { ctx } = this;
    const query = { limit: toInt(ctx.query.limit), offset: toInt(ctx.query.offset) };
    ctx.body = await ctx.model.User.findAll(query);
  }
  async show() {
    const { ctx } = this;
    ctx.body = await ctx.model.User.findByPk(toInt(ctx.params.id));
  }
  async create() {
    const { ctx } = this;
    const { nickname } = ctx.request.body;
    const user = await ctx.model.User.create({ nickname });
    ctx.status = 201;
    ctx.body = user;
  }
  async update() {
    const { ctx } = this;
    const id = toInt(ctx.params.id);
    const user = await ctx.model.User.findByPk(id);
    if (!user) {
      ctx.status = 404;
      return;
    }
    const { nickname } = ctx.request.body;
    await user.update({ nickname });
    ctx.body = user;
  }
  async destroy() {
    const { ctx } = this;
    const id = toInt(ctx.params.id);
    const user = await ctx.model.User.findByPk(id);
    if (!user) {
      ctx.status = 404;
      return;
    }
    await user.destroy();
    ctx.status = 200;
  }
}
module.exports = UserController;

 

  • router.js

 

'use strict';

/**
 * @param {Egg.Application} app - egg application
 */
module.exports = app => {
  const { router, controller } = app;
  router.get('/', controller.home.index);
  router.resources('user', '/user', controller.user);
};

 

postman測試

 

  • 查詢所有用戶
    • image.png
  • 根據id查找
    • image.png
  • 新增
    • image.png
  • 修改
    • image.png
  • 刪除
    • image.png

參考

    • image.png


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM