egg-sequelize
Sequelize plugin for Egg.js.
NOTE: This plugin just for integrate Sequelize into Egg.js, more documentation please visit http://sequelizejs.com.
Install
$ npm i --save egg-sequelize$ npm install --save mysql2 # For both mysql and mariadb dialects # Or use other database backend. $ npm install --save pg pg-hstore # PostgreSQL $ npm install --save tedious # MSSQL
Usage & configuration
Read the tutorials to see a full example.
- Enable plugin in
config/plugin.js
exportssequelize =enable: truepackage: 'egg-sequelize'
- Edit your own configurations in
conif/config.{env}.js
exportssequelize = 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;
You can also use the connection uri
to configure the connection:
exportssequelize = 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' { // if benchmark enabled, log used const used = typeof args1 === 'number' ? `[ms]` : ''; applogger; } host: 'localhost' port: 3306 username: 'root' benchmark: true define: freezeTableName: false underscored: true ;
More documents please refer to Sequelize.js
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
.
Examples
Standard
Define a model first.
NOTE:
options.delegate
default tomodel
, soapp.model
is an Instance of Sequelize, so you can use methods like:app.model.sync, app.model.query ...
// app/model/user.js module { const STRING INTEGER DATE = appSequelize; const User = appmodel; User { return await this; } // don't use arraw function Userprototype { return await this; } return User;};
Now you can use it in your controller:
// app/controller/user.js async { const users = await thisctxmodelUser; thisctxbody = users; } async { const user = await thisctxmodelUser; await user; thisctxbody = 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.jsexportssequelize = 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.jsmodule { const STRING INTEGER DATE = appSequelize; const User = appmodel; return User;}; // app/admin_model/user.jsmodule { const STRING INTEGER DATE = appSequelize; const User = appadminModel; 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 instancemodule { const STRING INTEGER DATE = appSequelize; const User = model; 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.jsexportssequelize = Sequelize: ;
Full example
// app/model/post.js module { const STRING INTEGER DATE = appSequelize; const Post = appmodel; Post { appmodelPost; } return Post;};
// app/controller/post.js async { const posts = await thisctxmodelPost; thisctxbody = posts; } async { const post = await thisctxmodelPost; const user = await post; post; thisctxbody = post; } async { const post = await thisctxmodelPost; await post; thisctxbody = 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.jsmodule { if appconfigenv === 'local' || appconfigenv === 'unittest' app; };
Migration
Using sequelize-cli to help manage your database, data structures and seed data. Please read Sequelize - Migrations to learn more infomations.
Recommended example
Questions & Suggestions
Please open an issue here.