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,删除后再创建

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值