Welcome to WuJiGu Developer Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
238 views
in Technique[技术] by (71.8m points)

mysql - Retriving data from another table and inserting it into new one sequelize

I've been working on a project that involves sequelize(MySQL DB).

So I have a table "InterestRate" that takes id's from two other tables(foreign keys).

table

bankId is stored in "Banks" table and interId is stored in another table called "Interest". Now I want to populate this table with Postman by sending this data:

{
    "bank": "BankName",
    "inter": "Interest",
    "nks": "4.11",
    "eks": "6.24",
    "time": "36"
}

BUT I want to populate table with the primary keys of these values(if existed in their own table). E.g When I send to postman I want to check table "Banks" and search "BankName" grab its id in that table, and put it in new table. Same thing for this inter thing.

Code that I have rn is trash, I know why it doesn't work but I'm really stuck.

(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);
    });
};

Note that all models etc. are set up correctly, it works if I enter things manually! Thank you!


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You just need to get Bank and Interest by names and use found model instances to get their ids to create InterestRate record:

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);
  }
};

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to WuJiGu Developer Q&A Community for programmer and developer-Open, Learning and Share
...