egg-model

1.0.3 • Public • Published

Egg Model

Build Status

基于 Sequelize 实现的 Egg 封装。

此插件是对 Sequelize 封装,一切细节,请看 Sequelize 的官方文档。

功能

  • 自动加载 app/model/*.js 成为 Model 文件,并初始化 Sequelize;
  • 增加 app.model, ctx.model 获得一个包含所有 Model 类的实例;
  • ctx.ModelName 可以直接访问 app/model/model_name.js,例如 ctx.User => app/model/user.js;
  • app.sequelize 可以获得已经初始化的 Sequelize 实例;
  • 结合 Egg 的日志,输出 SQL 查询,以及耗时;

配置

先在 plugin 里面启用 model 插件:

// config/plugin.js
exports.model = {
  enable: true,
  package: 'egg-model',
};

修改 config/config.default.js:

'use strict';
 
module.exports = {
  model: {
    dialect: "mysql",
    host: "127.0.0.1",
    database: "your-app-dev",
    username: "root",
    password: null,
    // Setup timezone
    timezone: '+08:00',
    // Setup charset
    dialectOptions: {
      charset: 'utf8'
    },
  },
};

修改 config/config.unittest.js:

'use strict';
 
module.exports = {
  model: {
    database: "your-app-test",
    // Disable Stdout log
    logging: false,
  },
};

修改 config/config.prod.js:

'use strict';
 
module.exports = {
  model: {
    database: "your-app-test",
  },
};

Model 文件

你可以在 app/model 下面创建 Sequelize 的 Model 文件,写法和 Sequelize 文档里面的方式一样,例如:

// app/model/user.js
'use strict';
 
module.exports = function(model, types) {
  const { STRING, INTEGER, TEXT, DATE } = types;
  return model.define('user', {
    login: {
      type: STRING,
      allowNull: false,
    },
    name: {
      type: STRING,
    },
    email: STRING,
    avatar: STRING,
    created_at: DATE,
    updated_at: DATE,
  }, {
 
    getterMethods: {
      fullName() {
        return `${this.login} (${this.name})`
      }
    }
 
    classMethods: {
      * findByLogin(login) {
        return yield this.findOne({ where: { login: login.toLowerCase() }});
      }
    },
  });
};

Egg 启动后,将会自动载入 app/model 里面的文件,并对应到 app 和 ctx 上下文里面。例如这个 User 你可以 app.Userctx.User 来调用。

Relations / Associations 声明

Sequelize 还包含 Relations / Associations,在 Egg 里面,你可以在建立 app/model/index.js 并在里面申明 Model 的 Relations 关系:

// app/model/index.js
'use strict';
 
module.exports = function(app) {
  const model = app.model;
 
  model.Post.belongsTo(model.User, { foreignKey: 'user_id' });
  model.Comment.belongsTo(model.User, { foreignKey: 'user_id' });
  model.User.hasMany(model.Comment, { foreignKey: 'user_id' })
  model.User.hasMany(model.Post, { foreignKey: 'user_id' })
};

测试

const eggModel = require('egg-model');
eggModel(app);
app.model.User.findAll({});

Dependents (0)

Package Sidebar

Install

npm i egg-model

Weekly Downloads

17

Version

1.0.3

License

MIT

Last publish

Collaborators

  • fengmk2
  • huacnlee