【发布时间】:2020-06-10 20:57:38
【问题描述】:
我正在使用 MySql 开发一个 React 前端 + Express 后端 API。
我在搞清楚在哪里进行 MySql 事务时遇到了一些麻烦。
我的 Express API 文件夹结构是这样的:
- API
- 型号/
- 控制器/
- 路线/
- app.js
Models/ 文件夹包含将 MySql 表的骨架保存为类的文件,其中调用数据库的方法作为静态方法。 models/ 文件夹中的文件之一(Student.js)如下所示:
// models/Student.js
const sql = require('./db'); // DB connection in this file
class Student {
constructor(student) {
this.id_student = student.id_student;
this.name = student.name;
this.surname = student.surname;
this.email = student.email;
this.current_year = student.current_year;
this.id_section = student.id_section;
}
static getAllStudents(callback) {
sql.query('SELECT * FROM student', (error, results) => {
if (error) {
console.log(`Error : ${error}`);
callback(null, error);
return;
}
console.log(`Elèves : ${JSON.stringify(results)}`);
callback(null, results);
});
};
}
在 controllers/ 文件夹中,student.js 文件如下所示:
// controllers/student.js
const Student = require('../models/Student');
exports.getAllStudents = (req, res) => {
Student.getAllStudents((error, students) => {
if (error) {
res.status(400).send(`Error retriving students - getAllStudents from controller/student.js - : ${error}`);
}
else {
res.status(200).json({ students });
}
})
};
在 routes/ 文件夹中,我只是调用相应的控制器,并根据路由使用它的方法。
关键是,我的模型/文件夹中有另一个文件(看起来像模型/Student.js):Section.js
我需要做一个事务来将值插入到学生表和部分表中(每个都表示为模型/文件夹中的单独文件,如解释的那样)。
问题:
- 我应该在哪里进行此交易?在模型/文件夹中的哪个文件中? Student.js 还是 Section.js ?还是另一种文件?如果是这样,在哪个文件夹中以及如何?
非常感谢您花时间帮助我
----- 更新 ------
这是表格关系的图片:
如您所见,Student表与Section有关系(其实我所说的Section表叫做section_relations表,是一个“链接表”)。
创建学生时,我首先检查学生表中的 id_section_group 和 id_section_promo 是否存在于 section_relations 表中。
如果没有,我想先创建部分(归档所有需要的 FK id)然后创建学生。这应该在一个事务中,将 FK id 插入到部分表中以创建部分,然后创建学生。
这应该在事务中完成,因为如果 2 个插入中的一个失败,它可以回滚。
非常感谢
【问题讨论】:
标签: javascript mysql node.js reactjs express