Node.js Sequelize关联错误无法读取未定义的属性“getTableName”
我遇到了一个问题,我收到了一条错误消息,Unhandled rejection TypeError:当我尝试将表关联到查询中时,无法读取undefined的属性“getTableName”。我在两个表之间有一对一的关系,不确定这是否是导致错误的原因,或者这是否是我关联这两个表的其他地方 我的问题是:Node.js Sequelize关联错误无法读取未定义的属性“getTableName”,node.js,sequelize.js,Node.js,Sequelize.js,我遇到了一个问题,我收到了一条错误消息,Unhandled rejection TypeError:当我尝试将表关联到查询中时,无法读取undefined的属性“getTableName”。我在两个表之间有一对一的关系,不确定这是否是导致错误的原因,或者这是否是我关联这两个表的其他地方 我的问题是: appRoutes.route('/settings') .get(function(req, res, organization){ models.DiscoverySo
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',{
user: req.user,
organization: organization,
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.belongsToMany(db.User, { through: 'member', foreignKey: 'user_id' });
},
}
});
return Organization;
}
您需要将查询重写为:
models.DiscoverySource.findAll({
attributes: ['discoverySource'],
where: {
organizationId: req.user.organizationId
},
include: [{
model: models.Organization,
attributes: ['organizationName', 'admin']
}]
})
根据Sequelize文档:
[选项.属性]-要选择的属性列表,或包含和排除键的对象
[选项。包括[]。属性]-要从子模型中选择的属性列表
[options.include[].至.where]-在连接模型上筛选归属关系
[选项.包括[]到.attributes]-要从连接模型中选择的属性列表,用于归属关系
因此,[options.include[].through]只能在属于多个关联的情况下使用,而不属于您用于DiscoverySource和Organization models的情况。我也面临同样的问题。我的续集版本5.22.3。 如果您使用的是同一版本,请对您的查询进行以下更改:
models.DiscoverySource.findAll({
attributes: ['discoverySource'],
where: {
organizationId: req.user.organizationId
},
include: {
model: models.Organization,
//rest of the code, if any
}
})
include不再需要是数组。在我的例子中
through: { attributes: [] }
解决了此问题。对于任何面临此问题的人,当您将数组以外的任何内容作为选项传递时,都会出现相同的错误。include[]参数