Eric Shell
Eric Shell

Reputation: 903

sequelize Model.hasOne Error: Model is not associated to ModelTwo

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.

Upvotes: 19

Views: 10646

Answers (2)

code-jaff
code-jaff

Reputation: 9330

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).

Upvotes: 28

Eric Shell
Eric Shell

Reputation: 903

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.

Upvotes: 6

Related Questions