eggjs与sequelize简单demo

情到浓时终转凉″ 提交于 2020-04-17 03:43:29

【推荐阅读】微服务还能火多久?>>>

参考 egg 官方文档

安装

// 依赖
npm install --save egg-sequelize mysql2
// ts 类型
npm install --save @types/sequelize

插件,config/plugin.ts

import { EggPlugin } from 'egg';

const plugin: EggPlugin = {
  sequelize: {
  sequelize: {
    enable: true,
    package: 'egg-sequelize'
  }
};

export default plugin;

配置,config/config.local.ts

import { EggAppConfig, PowerPartial } from 'egg';

export default () => {
  const config: PowerPartial<EggAppConfig> = {};

  config.sequelize = {
    dialect: 'mysql',
    host: '127.0.0.1',
    username: "root",
    password: '123456',
    port: 3306,
    database: 'csc',
  };
  
  return config;
};

实体类,app/model/user.ts

import { Application } from 'egg';

export default (app: Application) => {
  
  const { STRING, INTEGER, JSON } = app.Sequelize;

  const User = app.model.define('user', {
    id: { type: INTEGER, primaryKey: true, autoIncrement: true },
    name: STRING(30),
    age: INTEGER,
    info: JSON
  }, {
    tableName: 'user',
    underscored: true,
    timestamps: false,
  })
  
  return User
}

增删改查

import { Controller } from 'egg';

export default class HomeController extends Controller {

  public async index() {
    
    const { ctx } = this;
    ctx.body = await ctx.model.User.findAll();
    
  }
}
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!