Vue-Express项目中使用Sequelize创建MySQL行后如何获取返回ID
问题排查与修复方案
一、存在的核心问题
- 模型关联外键配置错误
- 后端路由规则与实际业务逻辑不匹配
- 后端接口异步逻辑存在漏洞
- 前端API调用参数传递不匹配
二、分步修复
1. 修复Sequelize模型关联错误
Case模型的hasMany和CaseImage模型的belongsTo外键配置错误,外键应该是caseId不是id:
Case模型修复:
Case.associate = (models) => { // 外键改为caseId,对应CaseImage表的caseId字段 Case.hasMany(models.caseimages, {foreignKey: 'caseId', as: 'images'}); };
CaseImage模型修复:
CaseImage.associate = (models) => { // 外键改为caseId CaseImage.belongsTo(models.cases, {foreignKey: 'caseId', as: 'case'}); };
2. 修复后端接口逻辑与路由
你当前的接口逻辑是同时创建Case和关联图片,不需要在路由上接收:id参数,同时修复异步逻辑(findOne和create都是异步方法需要加await):
路由修改:
// 去掉路径上的:id参数,因为是创建新Case不是给已有Case加图 app.post('/api/v1/cases/images', upload.single('file'), CaseImagesController.postImageWithCase)
Controller逻辑修复:
async postImageWithCase (req, res) { try { // 创建Case const caseResult = await Case.create({ caseName: req.body.caseName, constructionSite: req.body.constructionSite, createdBy: req.body.createdBy, dateOfDiscovery: req.body.dateOfDiscovery, dateOfRemoval: req.body.dateOfRemoval, responsible: req.body.responsible, howManyDiscoveries: req.body.howManyDiscoveries, placeOfDiscovery: req.body.placeOfDiscovery, text: req.body.text, sanction: req.body.sanction, forCompany: req.body.forCompany, priority: req.body.priority }) const newId = caseResult.id // 校验Case是否创建成功,异步方法加await const checkId = await Case.findOne({ where: {id: newId }}) if (checkId == null) { return res.status(400).send({ message: 'Prípad so zadaným ID sa nenašiel.'}) } // 创建图片记录,加await await CaseImage.create({ fileName: req.file.originalname, mimeType: req.file.mimetype, caseId: newId, path: req.file.path, }) // 可以把生成的caseId返回给前端方便后续使用 res.status(201).send({ message: 'Zistenie bolo úspešne vytvorené aj s fotografiou.', caseId: newId }) } catch (error) { console.log(error) res.status(400).send({ message: 'Nepodarilo sa pridať zistenie s fotografiou.'}) } }
3. 修复前端API调用逻辑
API方法修改: 不需要传id参数,匹配修改后的后端路由
postImageWithCase(bozpCase) { return Api().post('cases/images', bozpCase); }
Vue调用方法修改: 可以拿到返回的caseId做后续逻辑
async submitCaseWithPhotos() { try { const bozpCase = new FormData(); bozpCase.append('file', this.file); bozpCase.append('caseName', this.caseName); bozpCase.append('constructionSite', this.constructionSite); bozpCase.append('createdBy', this.logedUser); bozpCase.append('dateOfDiscovery', this.date); bozpCase.append('responsible', this.responsible); bozpCase.append('howManyDiscoveries', this.howManyDiscoveries); bozpCase.append('placeOfDiscovery', this.placeOfDiscovery); bozpCase.append('text', this.text); bozpCase.append('sanction', this.sanction); bozpCase.append('forCompany', this.forCompany); bozpCase.append('priority', this.priority); const response = await CaseImagesService.postImageWithCase(bozpCase) // 可以从response.data.caseId拿到生成的案件ID console.log('生成的案件ID:', response.data.caseId) this.$emit("close-card"); } catch (error) { console.log(error) this.error = "Failed to submit data - please try again later." } }
内容的提问来源于stack exchange,提问作者Marek
相关产品推荐
相关产品推荐

