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
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;
};
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With