在mysql workbench中使用node js将数据插入关联表

nue99wik  于 2024-01-05  发布在  Mysql
关注(0)|答案(1)|浏览(109)

我有两张table:乐器和性能(多对多关系)。我希望管理员可以创建一个包含许多乐器的性能。但我在插入关联表时出现了一些错误。关联表有perfprmanceId和instrumentId。我使用sequelize。下面是我的代码:
管理员控制器:

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


谢谢

5vf7fwbs

5vf7fwbs1#

根据您向我们显示的错误,似乎PerformanceInstrument未在您的代码中定义,这可能是因为您没有在文件中正确导入PerformanceInstrument模型。
确保在文件顶部的控制器处,您已经导入了模型。
范例:

const { PerformanceInstrument, Instrument } = require('../models'); // make sure you have the correct route

字符串

相关问题