sequelize Model.hasOne 错误:模型与 ModelTwo 无关 [英] sequelize Model.hasOne Error: Model is not associated to ModelTwo

查看:30
本文介绍了sequelize Model.hasOne 错误:模型与 ModelTwo 无关的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已将 sequelizejs 集成到我的 express 框架中.我配置了所有模型,并试图用它构建我的第一个查询.

I've integrated sequelizejs into my express framework. I got all the models configured and was trying to build my first query with it.

我不断收到错误错误:模型与 ModelTwo 无关!"

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

//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
};

关于可能出什么问题的任何想法?我正在使用最新版本的 sequelize 1.7.0-rc6.

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,

当我在包含模型时尝试使用 as 选项作为别名时,我遇到了同样的问题.只要您为默认名称设置别名,这不会引发错误,但如果您尝试不同的名称,则会出现错误.

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.

解决办法,

上面写得很清楚

如果关联是别名(使用 as 选项),您必须指定包含模型时的别名.

If an association is aliased (using the as option), you must specify this alias when including the model.

这意味着,反之亦然

如果您想在包含时为模型设置别名,则必须为其关联设置别名(使用 as 选项).

If you want to alias a model when including, it's association must be aliased (using the as option).

这篇关于sequelize Model.hasOne 错误:模型与 ModelTwo 无关的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆