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
You used
await
andthen
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:
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