Skip to content

Commit

Permalink
Supported to define associations in model module.
Browse files Browse the repository at this point in the history
  • Loading branch information
bow-fujita committed Nov 22, 2016
1 parent c5cc3fc commit d38459c
Show file tree
Hide file tree
Showing 3 changed files with 31 additions and 0 deletions.
2 changes: 2 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -342,6 +342,8 @@ Imports models into a Sequelize instance.

Each model module implemented in `opts.models` directory will be imported into a Sequelize instance after connection to a database is established.
The Sequelize instance will be returned with `Promise` upon success.
If a model module has `associate()` as a part of `classMethods`, it will be called with `sequelize.models` as its argument after all models are loaded.
So that it allows you to define [associations](http://docs.sequelizejs.com/en/v3/docs/associations/) between models.

`opts.database`, `opts.username` and `opts.password` are passed to [Sequelize's constructor](http://docs.sequelizejs.com/en/v3/api/sequelize/#class-sequelize).
Other options are also passed through to `options`, the 4th arugment of Sequelize's constructor.
Expand Down
8 changes: 8 additions & 0 deletions lib/model.js
Original file line number Diff line number Diff line change
Expand Up @@ -50,6 +50,14 @@ function load(opts, load_each)
load_each(path.join(dirname, name), sequelize, logging);
});

const models = sequelize.models;
_.keys(models).forEach((name) => {
const model = models[name];
if (_.isFunction(model.associate)) {
model.associate(models);
}
});

resolve(sequelize);
});
});
Expand Down
21 changes: 21 additions & 0 deletions test/models/task.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
/*!
* exprest4
* Copyright (c) 2016 Hiromitsu Fujita <bow.fujita@gmail.com>
* MIT License
*/

'use strict';

module.exports = (sequelize, DataTypes, schema) => {
return sequelize.define('task', {
title: DataTypes.STRING
, description: DataTypes.TEXT
}, {
schema: schema
, classMethods: {
associate: function(models) {
this.belongsTo(models.project, { as: 'project' });
}
}
});
};

0 comments on commit d38459c

Please sign in to comment.