我正在使用什么
node.js, express, sequelize 6.3.3, fast-csv 4.3.1 and mysql database.
我有的
我有一个包含以下标题和数据的 CSV 文件。
no, name, email, township, father_name, father_phone, mother_name, mother_phone, parent_township
在这个 CSV 中,我有两种类型的数据:students
和parents
.
在我的MySQL
数据库中,我有三个表:
students, parents and townships
学生表:
id, name, email, township_id
父母表:
id, student_id, father_name, father_phone, mother_name, mother_phone, parent_township_id
乡镇表:
id, name
我做了什么
fast-csv
我使用以下代码阅读了带有 npm 包的 CSV 。
let csvData = [];
fs.createReadStream(req.file.path)
.pipe(
csv.parse({
ignoreEmpty: true,
trim: true,
skipLines: 6,
})
)
.on("error", (error) => console.error(error))
.on("data", (row) => {
csvData.push(getHeaders(_.compact(row), csvStudentDataEntryFields));
})
.on("end", () => {
fs.unlinkSync(req.file.path);
const data = csvData.map((data) => {
const student = _.pick(data, studentFields);
const parent = _.pick(data, parentFields);
return [student, parent];
});
return res.status(201).send({
status: "success",
data,
});
});
我得到了什么
使用上面的代码,我得到data
了以下值。
[
[ // row 1 from CSV
{
"name": "John",
"email": "john@gmail.com",
"township": "NYC",
},
{
"fatherName": "Smith",
"fatherPhone": "9111111111",
"motherName": "Mary",
"motherPhone": "9111111111",
"parentTownship": "NYC"
}
],
[ // row 2 from CSV
{
"name": "Cutter",
"email": "cutter@gmail.com",
"township": "NYC",
},
{
"fatherName": "Laseli",
"fatherPhone": "9111111111",
"motherName": "Mary",
"motherPhone": "9111111111",
"parentTownship": "NYC"
}
]
]
我想要的是
我想将这些row 1
和row 2
from存储data
到数据库中的相应表中。
问题
我想我需要用真实 IDtownship
替换那些文本数据,因为我有如上所述的外键。
我怎样才能实现它?我想在数据库级别做到这一点。我不想id
在单独的 js 模块中查找该乡镇名称的名称。
更新
学生模型
class Student extends Model {
static associate(models) {
Student.belongsTo(models.Township, {
foreignKey: "townshipId",
as: "township",
targetKey: "townshipId",
});
Student.hasOne(models.Parent, {
foreignKey: "studentId",
as: "parent",
sourceKey: "studentId",
});
}
}
父模型
class Parent extends Model {
static associate(models) {
Parent.belongsTo(models.Student, {
foreignKey: "studentId",
as: "student",
targetKey: "studentId",
});
Parent.belongsTo(models.Township, {
foreignKey: "parentTownshipId",
as: "township",
targetKey: "townshipId",
});
}
}
乡镇模式
class Township extends Model {
static associate(models) {
Township.hasMany(models.Student, {
foreignKey: "townshipId",
as: "township",
sourceKey: "townshipId",
});
Township.hasMany(models.Parent, {
foreignKey: "townshipId",
as: "parentTownship",
sourceKey: "townshipId",
});
}
}
更新:
在我的控制器中,
let std = await models.Student.create(
{
nameEn: "John",
email: "john@gmail.com",
townshipId: 1,
parent: [{ ...d[1], parentTownshipId: 1 }],
},
{ include: ["parent"] }
);