通过表加紧与加载关联

我已经通过网站上的几个问题,但我仍然不能看到我在这里做错了什么,所以任何帮助将不胜感激。

我收到错误:

Organization (organizations) is not associated to User! 

组织模型:

 module.exports = function (sequelize, DataTypes) { return sequelize.define('Organization', { organizationID: { primaryKey: true, type: DataTypes.INTEGER(11), allowNull: false, }, name: { type: DataTypes.STRING, allowNull: false, }, description: { type: DataTypes.STRING, allowNull: true, } }, { tableName: "spa_vOrganization", freezeTableName: true, classMethods: { associate: function (models) { Organization.hasMany(models.User, { as: 'users', through: models.User_Tenant_Organization, foreignKey: 'organizationID' }); } }, }); }; 

用户模式:

 module.exports = function (sequelize, DataTypes) { return sequelize.define('User', { userID: { primaryKey: true, type: DataTypes.INTEGER(11), allowNull: false, }, password: { type: DataTypes.STRING, allowNull: false, }, email: { type: DataTypes.STRING, allowNull: false, } }, { tableName: "spa_User", freezeTableName: true, classMethods: { associate: function(models) { User.hasMany(models.Organization, { as: "organizations", through: models.User_Tenant_Organization, foreignKey: 'userID'}); } } } ); }; 

matrix表模型:

 module.exports = function (sequelize, DataTypes) { return sequelize.define('User_Tenant_Organization', { userTenantOrganizationID: { primaryKey: true, type: DataTypes.INTEGER(11), allowNull: false, }, userID: { type: DataTypes.INTEGER(11), allowNull: false, }, organizationID: { type: DataTypes.INTEGER(11), allowNull: false, }, tenantID: { type: DataTypes.INTEGER(11), allowNull: false, }, }, { tableName: "spa_User_Tenant_Organization", freezeTableName: true, }); }; 

我想要做的只是拉回一个用户与他们的组织急切地加载。 以下是我正在使用的:

 models.User.findOne({where: { email: body.email }, include: [ {model:models.Organization, as: 'organizations'}]}).complete( function (err, user) { // do something with the user } 

我已经试过UserOrganization都没有foreignKey定义,没有任何区别。 我显然误解了这些协会的一些事情。 任何人都可以告诉我哪里错了吗?

我发现了这个问题。 上面代码中的关联实际上是正确的 – 失败的是我的models / index.js,它是由yeoman generator自动生成的angular-express-sequelize

index.js循环遍历模型文件,将它们导入到sequelize对象中,并将一个副本存储在数组db []中,然后尝试运行classMethod associate(),但它调用models.options.associate()而不是models.associate():

 Object.keys(db).forEach(function (modelName) { if (db[modelName].options.hasOwnProperty('associate')) { db[modelName].options.associate(db); } }); 

我已经解决了通过删除“。选项”,一切工作正常。

拉请求解决这个问题在这里供参考: https : //github.com/rayokota/generator-angular-express-sequelize/pull/7