簡體   English   中英

從另一個表中檢索數據並將其插入到新表中

[英]Retriving data from another table and inserting it into new one sequelize

我一直在從事一個涉及 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);
    });
};

請注意,所有模型等都已正確設置,如果我手動輸入內容,它就可以工作! 謝謝!

您只需要按名稱獲取BankInterest並使用找到的 model 實例來獲取它們的 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);
  }
};

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM