Skip to content

eggjs/egg-sequelize

Repository files navigation

egg-sequelize

Sequelizeplugin for Egg.js.

NOTE: This plugin just for integrate Sequelize into Egg.js, more documentation please visithttp://sequelizejs.

NPM version build status Test coverage David deps Known Vulnerabilities npm download

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 thetutorialsto see a full example.

  • Enable plugin inconfig/plugin.js
exports.sequelize={
enable:true,
package:'egg-sequelize'
}
  • Edit your own configurations inconif/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
};

You can also use theconnection urito 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
constused=typeofargs[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,
},
};

More documents please refer toSequelize.js

Model files

Please put models underapp/modeldir 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.delegatedefault tomodel,soapp.modelis anInstance 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;

constUser=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=asyncfunction(login){
returnawaitthis.findOne({
where:{
login:login
}
});
}

// don't use arraw function
User.prototype.logSignin=asyncfunction(){
returnawaitthis.update({last_sign_in_at:newDate()});
}

returnUser;
};

Now you can use it in your controller:

// app/controller/user.js
classUserControllerextendsController{
asyncindex(){
constusers=awaitthis.ctx.model.User.findAll();
this.ctx.body=users;
}

asyncshow(){
constuser=awaitthis.ctx.model.User.findByLogin(this.ctx.params.login);
awaituser.logSignin();
this.ctx.body=user;
}
}

Associate

Define all your associations inModel.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 useconfig.sequelize.datasourcesto 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;

constUser=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,
});

returnUser;
};

// app/admin_model/user.js
module.exports=app=>{
const{STRING,INTEGER,DATE}=app.Sequelize;

constUser=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,
});

returnUser;
};

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;

constUser=model.define('user',{
login:STRING,
name:STRING(30),
password:STRING(32),
age:INTEGER,
last_sign_in_at:DATE,
created_at:DATE,
updated_at:DATE,
});

returnUser;
};

Customize Sequelize

By default, egg-sequelize will use sequelize@5, you can cusomize sequelize version by pass sequelize instance withconfig.sequelize.Sequelizelike 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;

constPost=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'});
}

returnPost;
};
// app/controller/post.js
classPostControllerextendsController{
asyncindex(){
constposts=awaitthis.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;
}

asyncshow(){
constpost=awaitthis.ctx.model.Post.findByPk(this.params.id);
constuser=awaitpost.getUser();
post.setDataValue('user',user);
this.ctx.body=post;
}

asyncdestroy(){
constpost=awaitthis.ctx.model.Post.findByPk(this.params.id);
awaitpost.destroy();
this.ctx.body={success:true};
}
}

Sync model to db

We strongly recommend you to useSequelize - Migrationsto 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()=>{
awaitapp.model.sync({force:true});
});
}
};

Migration

Usingsequelize-clito help manage your database, data structures and seed data. Please readSequelize - Migrationsto learn more infomations.

Recommended example

Questions & Suggestions

Please open an issuehere.

License

MIT