我一直在做一个涉及 sequelize(MySQL DB) 的项目。
所以我有一个表“InterestRate”,它从其他两个表(外键)中获取 id。
bankId 存储在“Banks”表中,interId 存储在另一个名为“Interest”的表中。
现在我想通过发送以下数据用 Postman 填充此表:
{
"bank": "BankName",
"inter": "Interest",
"nks": "4.11",
"eks": "6.24",
"time": "36"
}
但是 我想用这些值的主键填充表(如果存在于它们自己的表中)。例如,当我发送给 postman 时,我想检查表“Banks”并搜索“BankName”,在该表中获取其 ID,并将其放入新表中。对于这个内部的事情,同样的事情。我的代码是垃圾,我知道为什么它不起作用,但我真的被卡住了。
(req, res) => {
const bank = req.body.bank;
const type = req.body.type;
const nks = req.body.nks;
const eks = req.body.eks;
const time = req.body.time;
InterestRate.create({
bankId: bank,
interId: type,
NKS: nks,
EKS: eks,
time: time,
})
.then(() => {
res.status(200).json({ message: 'Added successfully' });
})
.catch((err) => {
res.status(500).send('Error -> ' + err);
});
};
请注意,所有模型等都已正确设置,如果我手动输入内容,它会起作用!谢谢!
最佳答案
您只需要通过名称获取 Bank
和 Interest
并使用找到的模型实例来获取它们的 id 以创建 InterestRate
记录:
async (req, res) => {
const bank = req.body.bank;
const type = req.body.type;
const nks = req.body.nks;
const eks = req.body.eks;
const time = req.body.time;
const foundBank = await Bank.findOne({
where: {
name: bank // use a real field name instead of "name"
}
})
const foundInterest = await Interest.findOne({
where: {
name: type // use a real field name instead of "name"
}
})
if(!foundBank) {
// here should be some "res.status(...).send(...)" with error message
return
}
if(!foundInterest) {
// here should be some "res.status(...).send(...)" with error message
return
}
try {
await InterestRate.create({
bankId: foundBank.id,
interId: foundInterest.id,
NKS: nks,
EKS: eks,
time: time,
})
res.status(200).json({ message: 'Added successfully' });
catch (err) {
res.status(500).send('Error -> ' + err);
}
};
关于mysql - 从另一个表中检索数据并将其插入到新表中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65669889/