gpt4 book ai didi

node.js - Sequelize 关联错误无法读取未定义的属性 'getTableName'

转载 作者:搜寻专家 更新时间:2023-10-31 23:16:56 24 4
gpt4 key购买 nike

我遇到了一个问题,当我尝试将表关联到我的查询时,我收到一条错误消息,Unhandled rejection TypeError: Cannot read property 'getTableName' of undefined。我在表之间有一对一的关系,我不确定这是否导致了错误,或者它是否在我关联两个表的其他地方。

这是我的查询:

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
});
})

})

这是 models.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.attributes] - A list of the attributes that you want to select, or an object with include and exclude keys.

[options.include[].attributes] - A list of attributes to select from the child model.

[options.include[].through.where] - Filter on the join model for belongsToMany relations.

[options.include[].through.attributes] - A list of attributes to select from the join model for belongsToMany relations.

因此,[options.include[].through] 只能用于 Belongs-To-Many 关联,而不是 Belong-To 用于 DiscoverySourceOrganization 模型。

关于node.js - Sequelize 关联错误无法读取未定义的属性 'getTableName',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35974514/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com