Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using Sequelize with associations and scopes with includes in multiple files

I'm using this way to keep my Sequelize models in separate files and everything works pretty well but now I came up with the idea to have scopes with includes in it.

Something like this doesn't work:

var User = sequelize.define("User", {...}, {
  scopes: {
    complete: {
      include: [{
        model: Task
      }]
    }
  }
});

... Since Task is (of course) not defined. Even using require('.').Task instead doesn't help at this point because User gets loaded before Task and by the time User is loaded, Task is not yet defined.

So, is there a simple and easy way without a dozen workarounds to have

  • associations
  • scopes with includes
  • ... All of this in a separate file per model?
like image 283
Manuel Bieh Avatar asked Dec 05 '22 01:12

Manuel Bieh


1 Answers

and if the model (Task) is not yet loaded? (in this case T comes before U and the model is loaded).

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

becomes

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

Object.keys(db).forEach(function(modelName) {
  if ("loadScopes" in db[modelName]) {
    db[modelName].loadScopes(db);
  }
});

and the model

module.exports = function(sequelize, DataTypes) {
  var User = sequelize.define("User", {
    username: DataTypes.STRING
  }, {
    classMethods: {
      associate: function(models) {
        User.hasMany(models.Task)
      }
    }
  });

  return User;
};

becomes

module.exports = function(sequelize, DataTypes) {
  var User = sequelize.define("User", {
    username: DataTypes.STRING
  }, {
    classMethods: {
      associate: function(models) {
        User.hasMany(models.Task)
      }

      loadScopes: function(models) {
        User.addScope('complete', {
          include: [{
            model: models.Task
          }]
        })
      }

    }
  });

  return User;
};
like image 95
user257253 Avatar answered May 14 '23 19:05

user257253