Skip to content

Instantly share code, notes, and snippets.

@elvis-onobo
Created December 10, 2020 12:44
Show Gist options
  • Save elvis-onobo/716f346c71d1873fe72af0677bad0263 to your computer and use it in GitHub Desktop.
Save elvis-onobo/716f346c71d1873fe72af0677bad0263 to your computer and use it in GitHub Desktop.
const User = use('App/Models/user')
const Article = use('App/Models/Article')
const Database = use('Database')
async createArticleWithUser({ request, response, session }) {
const trx = await Database.beginTransaction()
try{
const { topic } = request.post()
const user = new User()
// pass the transaction object
await user.save(trx)
const user_id = user.id
const article = new Article()
article.user_id = user_id
article.topic = topic
await article.save(trx);
// once done commit the transaction
trx.commit()
}catch(e){
console.log('There has been an error >>', e)
// rollback the transaction if it fails for any reason
await trx.rollback()
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment