我有2个表:乐器和性能(多对多关系)。我希望管理员可以创建包含许多乐器的表演。但是插入关联表时出现一些错误。关联表有perfprmanceId和instrumentId。我正在使用续集。这是我的代码:
管理员控制器:
postCreatePerformance = (req, res, next) => {
const title = req.body.title;
const date = req.body.date;
const location = req.body.location;
const instrumentNames = req.body.instrumentNames;
req.user
.createPerformance({
title: title,
date: date,
location: location,
})
.then(createdPerformance => {
return Instrument.findAll({
where: { title: instrumentNames },
attributes: ['id'],
});
})
.then(instruments => {
//insert data into associative table
const performanceInstrumentData = instruments.map(instrumentId => ({
performanceId: createdPerformance.id,
instrumentId: instrumentId,
}));
return PerformanceInstrument.bulkCreate(performanceInstrumentData);
})
.then(() => {
console.log('Created performance');
res.redirect('/');
})
.catch(error => {
console.error('Error creating performance or instruments:', error);
// res.redirect('/');
});
};
错误:
Error creating performance or instruments: ReferenceError: PerformanceInstrument is not defined
谢谢
根据您向我们展示的错误,您的代码中似乎未定义 PerformanceInstrument,这可能是因为您没有在文件中正确导入 PerformanceInstrument 模型。
确保在控制器所在的文件顶部已导入模型。
示例:
const { PerformanceInstrument, Instrument } = require('../models'); // make sure you have the correct route