我遇到了一个问题,我试图关联两个具有一对多关系的模型。出于某种原因,尽管引用了这种关系,但这个查询仍会抛出错误。
这是我的错误消息:
Unhandled rejection TypeError: Cannot read property 'getTableName' of undefined
at generateJoinQueries (/Users/user/Desktop/Projects/node/project/node_modules/sequelize/lib/dialects/abstract/query-generator.js:1181:43)
这是路线:
appRoutes.route('/settings')
.get(function(req, res, organization){
models.DiscoverySource.findAll({
where: {
organizationId: req.user.organizationId
},
include: [{
model: models.Organization, through: { attributes: ['organizationName', 'admin', 'discoverySource']}
}]
}).then(function(organization, discoverySource){
res.render('pages/app/settings.hbs',{
organization: organization,
discoverySource: discoverySource
});
})
});
DiscoverySource:
module.exports = function(sequelize, DataTypes) {
var DiscoverySource = sequelize.define('discovery_source', {
discoverySourceId: {
type: DataTypes.INTEGER,
field: 'discovery_source_id',
autoIncrement: true,
primaryKey: true
},
discoverySource: {
type: DataTypes.STRING,
field: 'discovery_source_name'
},
organizationId: {
type: DataTypes.TEXT,
field: 'organization_id'
},
},{
freezeTableName: true,
classMethods: {
associate: function(db) {
DiscoverySource.belongsTo(db.Organization, {foreignKey: 'organization_id'});
},
},
});
return DiscoverySource;
}
组织:
module.exports = function(sequelize, DataTypes) {
var Organization = sequelize.define('organization', {
organizationId: {
type: DataTypes.INTEGER,
field: 'organization_id',
autoIncrement: true,
primaryKey: true
},
organizationName: {
type: DataTypes.STRING,
field: 'organization_name'
},
admin: DataTypes.STRING
},{
freezeTableName: true,
classMethods: {
associate: function(db) {
Organization.hasMany(db.DiscoverySource, {foreignKey: 'organization_id'});
},
}
});
return Organization;
}
答案 0 :(得分:2)
看起来,这是Sequelize Association Error Cannot read property 'getTableName' of undefined的副本。
但是,您需要将查询重写为:
models.DiscoverySource.findAll({
attributes: ['discoverySource'],
where: {
organizationId: req.user.organizationId
},
include: [{
model: models.Organization,
attributes: ['organizationName', 'admin']
}]
})
根据Sequelize文档:
[options.attributes] - 要选择的属性列表,或包含include和exclude键的对象。
[options.include []。attributes] - 要从子模型中选择的属性列表。
[options.include []。through.where] - 过滤关于belongsToMany关系的连接模型。
[options.include []。through.attributes] - 要从belongsToMany关系的连接模型中选择的属性列表。
因此,[options.include[].through]
只能用于Belongs-To-Many
关联而不是Belong-To
用于DiscoverySource
和Organization
模型的情况。