如何从插入中获取返回值并在插入其他元素后使用它

时间:2019-05-10 12:57:56

标签: sql postgresql

如何保存test_id并用它在一个SQL事务中将tests_questions表中的行插入(下面的代码很快)

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

0 个答案:

没有答案