I've integrated sequelizejs into my express framework. I got all the models configured and was trying to build my first query with it.
I keep getting the error "Error: Model is not associated to ModelTwo!"
app.get('/',function(req,res){
db.Member.findAll({include:[{model:db.MemberProfile,as:'Profile'}]})
.success(function(users){
if(users){
res.json(users);
}else{
res.send('no users');
}
});
});
// model.js
module.exports = function(sequelize,sql) {
return sequelize.define('Model', {
//attributes
});
Model.hasOne('ModelTwo',{foreignKey:'model_id'});
};
//model_two.js
module.exports = function(sequelize,sql) {
return sequelize.define('ModelTwo', {
//attributes
});
//no relationship defined. Tried ModelTwo.hasMany('Model',{foreignKey:'id'});
//but it yields the same resulting error
};
Any ideas as to what may be going wrong? I'm using the latest version of sequelize 1.7.0-rc6.
This is actually another case which throws the same error,
I ran in to the same issue when I try to use as
option for aliasing when including the model. This will not throw an error as long as you aliased the default name, but you'll get error if you try different name.
The solution,
It clearly says
If an association is aliased (using the
as
option), you must specify this alias when including the model.
This means that, the vise versa as well
If you want to alias a model when including, it's association must be aliased (using the
as
option).
I figured it out. It seems I needed to use the following in the model definition to add associations instead of the simple Model.hasOne(bla) which is in the documentation.
classMethods:{
associate:function(models){
Model.hasOne(models.ModelTwo,{foreignKey:'foreign_key'})
}
}
This code was in the tutorial for express on their site, not in the association documentation.
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