Sequelize Insert transaction (two tables, multiple rows)

2k views Asked by At

Two tables: post and post_resources. The logic I want to implement: Whenever I add data to post table, I want to add resources as well to the post_resources table, with the same foreign key of PostId

How I'm doing it:

const post = {
    name: req.body.title,
    description: req.body.description,
}

try {
  const result = await sq.transaction(async (t) => {
     await Post.create(post, { transaction: t })
          .then(async data => {
               await PostResources.create({
                   PostId: data.id,
                   name: req.body.title,
                   url: req.body.url,
                }, { transaction: t })
           })
     });

     res.status(200).json(result)

} catch (error) {
       console.log(error || 'Error occured in transaction');
}

Ps: the url is an array of urls to insert into post_ressources along with the same PostId !important

Please feel free to ask for any further details, thank you

1

There are 1 answers

1
Alexandru DuDu On BEST ANSWER

You used await and then in the same time, which is a mistake because they are similar.

Your error says that you already commited the transaction so a solution would be like this:

const post = {
    name: req.body.title,
    description: req.body.description,
}
const t = await sequelize.transaction();
try {
     const resultPost = await Post.create(post, { transaction: t })
     const resultPostResources = await PostResources.create({
        PostId: resultPost.id,
        name: req.body.title,
        url: req.body.url,
        }, {transaction: t})
     await t.commit();
     res.status(200).json(result)
}catch (error) {
     console.log(error || 'Error occured in transaction');
}

Now you commit the transaction only after both Creation queries and also you get the values from the first one to use in second one.

Note that create returns the created object, so you can make use of it