Custom .find() tied to a Sequelize Model

451 Views Asked by At

Couldn't find what I wanted in the documentation, so I'm just going to leave this here and hope for some help!

I have a specific query that I need to run on my user Model with a lot of includes and those includes all have where statements inside of them... So, I'd like to unclutter my controller and put this logic

User.findById(userId, {include: [{ model: Model1, where: { aCondition: false} },{ model: Model2, where: { aCondition: false} },{ model: Model3, where: { aCondition: false} },{ model: Model4, where: { aCondition: false} },{ model: Model5, where: { aCondition: false} }]}).then() into the Model itself so I'd just be able to call

User.findByIdWithIncludes(userId).then() inside of my controller.

Does this functionality exist and I'm just missing it?

Any help/advice would be greatly appreciated.

Thanks!

2

There are 2 best solutions below

0
On BEST ANSWER

This kind of select can be done with the use of "Scopes", http://sequelize.readthedocs.org/en/latest/docs/scopes/

By defining your models like that:

var Project = sequelize.define('Model1', {
  // Attributes
}, {
  defaultScope: {
    where: {
      aCondition: false
    }
  }
});

It will be used with every find(). You can define multiple scopes.

1
On

Give a look at http://sequelize.readthedocs.org/en/latest/docs/models-definition/#expansion-of-models

That definitely gives you the chance to create a findByIdWithIncludes method on your Model