0

How can I save test_id and after use it to insert rows in tests_questions table in one sql transaction (below code is fast)

const [{ test_id }] = await db.any(`
        INSERT INTO tests (name, descr, show)
          VALUES ('${name}', '${descr}', ${show})
          RETURNING test_id;
      `)

      if (questions && questions.length) {
        questions.map(async (question) => {
          const [{ tests_question_id }] = await db.any(`
            INSERT INTO tests_questions (test_id, name, code)
              VALUES (${test_id}, '${question.name}', '${question.code}')
              RETURNING tests_question_id;
          `)

          if (question.answers && question.answers.length) {
            question.answers.map(async (answer) => {
              await db.any(`
                INSERT INTO tests_questions_answers (tests_question_id, name, is_true)
                  VALUES (${tests_question_id}, '${answer.name}', ${answer.isTrue});
              `)
            })
          }
        })
      }
Skrface
  • 1,330
  • 1
  • 11
  • 19
  • I think there is a lack of tag in your problem description. What is the language around the SQL? And could you, please, put a sample of data you have and the data you want after treatment? – Jaisus May 10 '19 at 13:40
  • This link might help: https://stackoverflow.com/questions/2944297/postgresql-function-for-last-inserted-id – Amélie Dupré May 10 '19 at 14:03

0 Answers0