1 Star 1 Fork 0

Rong姐姐好可爱 / egg-sequelize-plus

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
克隆/下载
贡献代码
同步代码
取消
提示: 由于 Git 不支持空文件夾,创建文件夹后会生成空的 .keep 文件
Loading...
README
MIT

egg-sequelize-plus

NPM version Test coverage

Known Vulnerabilities npm download

Sequelize plugin for Egg.js,Based on egg-sequelize at present

NOTE: This plug-in integrates sequelize to egg.js on the basis of egg sequelize, provides dynamic database creation, realizes data dynamic deployment, and is perfectly compatible with all functions of the current egg sequelize plug-in more documentation please visit sequelize and egg-sequelize

egg-sequelize-plus egg 1.x
1.x 😁
0.x

Install

$ npm i egg-sequelize-plus --save

If the egg project fails to start and reminds mysql2 or sequelize module that it cannot be found , just like this

could not find module 'mysql2' 
// or 
could not find module 'sequelize'

you can try the following command

$ npm install mysql2 --save
// or 
$ npm install sequelize --save

Usage

// {app_root}/config/plugin.js
exports.sequelizePlus = {
  enable: true,
  package: 'egg-sequelize-plus',
};

Configuration

// {app_root}/config/config.default.js
exports.sequelizePlus = {
  dialect: 'mysql', // support: mysql, mariadb, postgres, mssql 
  database: 'test',
  host: 'localhost', //default
  port: 3306,
  username: 'root', // default
  password: 'root', // default
  // 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
  logging: false,
  options: {
    timezone: 'Asia/Shanghai',
    pool: {
      maxConnections: 5,
    },
  },
};

You can also use the connection uri to configure the connection:

exports.sequelize = {
  dialect: 'mysql', // support: mysql, mariadb, postgres, mssql
  connectionUri: 'mysql://root:@127.0.0.1:3306/test',
  // 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
};

egg-sequelize has a default sequelize options below

{
    delegate: 'model',
    baseDir: 'model',
    logging(...args) {
      // if benchmark enabled, log used
      const used = typeof args[1] === 'number' ? `[${args[1]}ms]` : '';
      app.logger.info('[egg-sequelize]%s %s', used, args[0]);
    },
    host: 'localhost',
    port: 3306,
    username: 'root',
    benchmark: true,
    define: {
      freezeTableName: false,
      underscored: true,
    },
  }

see config/config.default.js for more detail and default config

Model files

Please put models under app/model dir by default.

Conventions

model file class name
user.js app.model.User
person.js app.model.Person
user_group.js app.model.UserGroup
user/profile.js app.model.User.Profile
  • Tables always has timestamp fields: created_at datetime, updated_at datetime.
  • Use underscore style column name, for example: user_id, comments_count.

Standard

Define a model first.

NOTE: options.delegate default to model, so app.model is an Instance of Sequelize, so you can use methods like: app.model.sync, app.model.query ...

// app/model/user.js 
module.exports = app => {  
  const { STRING, INTEGER, DATE } = app.Sequelize; 
    const User = app.model.define('user', {    
    login: STRING,    
    name: STRING(30),    
    password: STRING(32),    
    age: INTEGER,    
    last_sign_in_at: DATE,    
    created_at: DATE,    
    updated_at: DATE,  
  });   
  User.findByLogin = async function(login) {        
    return await this.findOne({      
      where: {        
        login: login      
        }    
      });
    }   
// don't use arraw function  
User.prototype.logSignin = async function() {    
  return await this.update({ 
    last_sign_in_at: new Date() 
    }); 
  } 
  return User;
}; 

Now you can use it in your controller:

// app/controller/user.js
class UserController extends Controller {  
  async index() {    
  const users = await this.ctx.model.User.findAll();
  this.ctx.body = users;
  }
  async show() {
  const user = await this.ctx.model.User.findByLogin(this.ctx.params.login);    
  await user.logSignin();
  this.ctx.body = user;
}

Associate

Define all your associations in Model.associate() and egg-sequelize will execute it after all models loaded. See example below.

Multiple Datasources

egg-sequelize support load multiple datasources independently. You can use config.sequelize.datasources to configure and load multiple datasources.

// config/config.default.js
exports.sequelize = {  
  datasources: [{     
     delegate: 'model', // load all models to app.model and ctx.model 
     baseDir: 'model', // load models from `app/model/*.js`
     database: 'biz',      // other sequelize configurations
  },    
  {      
    delegate: 'admninModel', // load all models to app.adminModel and ctx.adminModel 
    baseDir: 'admin_model', // load models from `app/admin_model/*.js` 
    database: 'admin',      // other sequelize configurations
   }]
};

Then we can define model like this:

// app/model/user.js
module.exports = app => {
    const { STRING, INTEGER, DATE } = app.Sequelize;
    const User = app.model.define('user', {
      login: STRING,
      name: STRING(30),
      password: STRING(32),
      age: INTEGER,
      last_sign_in_at: DATE,
      created_at: DATE,        
      updated_at: DATE,
    });  
    return User;
}; 
// app/admin_model/user.js
module.exports = app => { 
    const { STRING, INTEGER, DATE } = app.Sequelize;
    const User = app.adminModel.define('user', { 
    login: STRING, 
    name: STRING(30), 
    password: STRING(32),
    age: INTEGER, 
    last_sign_in_at: DATE,
    created_at: DATE, 
    updated_at: DATE, 
  });
  return User;
};

If you define the same model for different datasource, the same model file will be excute twice for different database, so we can use the secound argument to get the sequelize instance:

// app/model/user.js
// if this file will load multiple times for different datasource
// we can use the secound argument to get the sequelize instance
module.exports = (app, model) => {
    const { STRING, INTEGER, DATE } = app.Sequelize;
    const User = model.define('user', {
    login: STRING,
    name: STRING(30),
    password: STRING(32),
    age: INTEGER,    
    last_sign_in_at: DATE,    
    created_at: DATE,    
    updated_at: DATE, 
    });   
    return User;
};

Customize Sequelize

By default, egg-sequelize will use sequelize@5, you can cusomize sequelize version by pass sequelize instance with config.sequelize.Sequelize like this:

// config/config.default.js
exports.sequelize = { 
   Sequelize: require('sequelize');
};

Full example

// app/model/post.js
 module.exports = app => {  
   const { STRING, INTEGER, DATE } = app.Sequelize;   
   const Post = app.model.define('Post', {    
     name: STRING(30),    
     user_id: INTEGER,    
     created_at: DATE,    
     updated_at: DATE,  });   
     Post.associate = function() {    
       app.model.Post.belongsTo(app.model.User, { 
         as: 'user' 
       }); 
      }   
    return Post;
     };
// app/controller/post.js
class PostController extends Controller {  a
  async index() {    
    const posts = await this.ctx.model.Post.findAll({      
      attributes: [ 'id', 'user_id' ],      
      include: { model: this.ctx.model.User, as: 'user' },      
      where: { status: 'publish' },      
      order: 'id desc',    });     
      this.ctx.body = posts;  
  }   
  async show() {    
    const post = await this.ctx.model.Post.findByPk(this.params.id);    const user = await post.getUser();    
    post.setDataValue('user', user);    
    this.ctx.body = post;  
  }   
  async destroy() {    
    const post = await this.ctx.model.Post.findByPk(this.params.id);    await post.destroy();    
    this.ctx.body = { 
      success: true 
    };  
  }
}

Sync model to db

We strongly recommend you to use Sequelize - Migrations to create or migrate database.

This code should only be used in development.

// {app_root}/app.js
module.exports = app => {  
  if (app.config.env === 'local' || app.config.env === 'unittest') {    
    app.beforeStart(async () => {      
    await app.model.sync({force: true});    
    });  
}};

Questions & Suggestions

Please open an issue here.

Author

Taylor

License

MIT

The MIT License (MIT) Copyright (c) 2019-present Alibaba Group Holding Limited and other contributors. Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

简介

基于egg-sequelize插件针对数据库动态部署、连接等功能进行封装,兼容egg-sequelize插件的所有配置和功能,解决egg-sequelize连接数据库无法实现数据库动态部署的痛点,欢迎大家使用和相互交流学习,有问题及时issues,觉得不错帮忙star一下 展开 收起
JavaScript
MIT
取消

发行版

暂无发行版

贡献者

全部

近期动态

加载更多
不能加载更多了
JavaScript
1
https://gitee.com/mmdapl/egg-sequelize-plus.git
git@gitee.com:mmdapl/egg-sequelize-plus.git
mmdapl
egg-sequelize-plus
egg-sequelize-plus
master

搜索帮助