Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 494
Eric Shell Avatar asked Feb 17 '14 17:02

Eric Shell


2 Answers

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

like image 166
code-jaff Avatar answered Oct 21 '22 05:10

code-jaff


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.

like image 30
Eric Shell Avatar answered Oct 21 '22 04:10

Eric Shell