javascript sequelize Model.hasOne 错误:模型与 ModelTwo 无关

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/21835827/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-27 21:47:29  来源:igfitidea点击:

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

javascriptsqlnode.jssequelize.js

提问by Eric Shell

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

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

I keep getting the error "Error: Model is not associated to ModelTwo!"

我不断收到错误“错误:模型与 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

// 模型.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
};

Any ideas as to what may be going wrong? I'm using the latest version of sequelize 1.7.0-rc6.

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

回答by code-jaff

This is actually another casewhich throws the same error,

这实际上是另一种抛出相同错误的情况,

I ran in to the same issue when I try to use asoption 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在包含模型时使用别名选项时遇到了同样的问题。只要您为默认名称设置别名,这不会引发错误,但如果您尝试不同的名称,则会出现错误。

The solution,

解决方案,

It clearly says

它清楚地说

If an association is aliased (using the asoption), you must specifythis alias when including the model.

如果关联具有别名(使用该as选项),则必须在包含模型时指定此别名。

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

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

回答by Eric Shell

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.

我想到了。似乎我需要在模型定义中使用以下内容来添加关联,而不是文档中的简单 Model.hasOne(bla) 。

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.

这段代码在他们网站上的 express 教程中,而不是在关联文档中。