sequelize Model.hasOne 错误:模型未关联到 ModelTwo [英] sequelize Model.hasOne Error: Model is not associated to ModelTwo

查看:11
本文介绍了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');
  }
 });
});

//模型.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天全站免登陆