egg框架结合egg-sequelize 建立数据库链接

安装

$ npm i --save egg-sequelize
$ npm install --save mysql2 //For both mysql and mariadb dialects

使用和配置

Enable plugin in config/plugin.js

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

Edit your own configurations in config/config.{env}.js

exports.sequelize = {
  dialect: 'mysql', // support: mysql, mariadb, postgres, mssql
  database: 'test',
  host: 'localhost',
  port: 3306,
  username: 'root',
  password: '',
  // delegate: 'myModel', // load all models to `app[delegate]` and `ctx[delegate]`, default to `model`
  // baseDir: 'my_model', // load all files in `app/${baseDir}` as models, default to `model`
  // exclude: 'index.js', // ignore `app/${baseDir}/index.js` when load models, support glob and array
  // more sequelize options
};

建立模型文件

Edit your own model in app/model/users.js

const { STRING, INTEGER } = app.Sequelize;
    const Users = app.model.define('users', {
        id: { type: INTEGER, primaryKey: true, autoIncrement: true },
        userid: STRING(30),
    },{
        freezeTableName: true, // Model 对应的表名将与model名相同
        timestamps: true, // 自动处理时间戳
    });
    app.model.Users = Users;
    return Users;

方法调用

在 app/controller/user.js

const user = await ctx.model.Users.create({userid:'123'});
      console.log(user)

将模型同步到数据库

建议您使用Sequelize-Migrations创建或迁移数据库

// {app_root}/app.js
module.exports = app => {
  app.beforeStart(async () => {
      await app.model.sync({force: false,alter:true});
    });
};
force // false 为不覆盖 true会删除再创建(慎用)
alter // true可以 添加或删除字段

可以能遇到的问题

1.Table ‘conceptstore.user’ doesn’t exist
由于之前的不正常操作,导致内部表冲突,无法创建表;
解决办法:app.js force设置为true,删除后再创建

你可能感兴趣的:(js)