Welder Marcos
Welder Marcos

Reputation: 129

Define sequelize associations in separated file

I'm using sequelize and sequelize-auto packages to manage my models, but everytime that I need to re-generete the models as result from a modification in the database I need to redefine te associations all over again since the associations are defined in classMethods in model file.

There is some way do define the associations in different file?

Upvotes: 1

Views: 2614

Answers (2)

Eggon
Eggon

Reputation: 2356

I came with a similar solution, but seems even simpler. Each model is defined in a separate file imported to the associations file where models are connected in a function. That function is imported, executed and assigned to a variable in the server file. It works.

associations.js file:

Model1 = require('./Model1')
Model2 = require('./Model2')

const setAssociations = function() {
   Model1.belongsTo(Model2)
}
module.exports = setAssociations;

server.js file:

const Associations = require('./models/associations')();

Upvotes: 3

Welder Marcos
Welder Marcos

Reputation: 129

The best solution I've found at the present time is to create a file like 'associations.js' outside the sequelize models folder whith content like this:

module.exports = function (models) {

  models.model1.hasMany(models.model2, {
    onDelete: 'cascade',
    foreignKey: 'model1123'
  });

  models.model1.Instance.prototype.getTimes = function () {
    return this.x * 100;
  }
};

In this file you will setup all the relations and the instance methods for each model in ypur aplication. As you can see you need to pass the models object for it to work, for this in your models/index.js:

'use strict'

...

Object.keys(db).forEach(function (modelName) {
  if (db[modelName].associate) {
    db[modelName].associate(db);
  }
});

require('../utils/associations')(db);

db.sequelize = sequelize;
db.Sequelize = Sequelize;

module.exports = db;

Just require the module passing the sequelize object after it has been initialized.

Hope it can help someone else.

Upvotes: 2

Related Questions