Database transaction with bulk insert


#1

How to bulk insert when using db transaction ?

// BULK INSERT
const firstUserId = await Database
  .from('users')
  .insert([{username: 'foo'}, {username: 'bar'}])
const trx = await Database.beginTransaction()
await trx.insert([{username: 'foo'}, {username: 'bar'}])).into('users')

What is the proper way to do that


#2

I think there are two way to achieve this.

  1. Using Database instance (knex.js) - https://knexjs.org/#Utility-BatchInsert
  2. Using Lucid Model - https://adonisjs.com/docs/4.0/lucid#_createmany

if you are using lucid model, just pass the trx you declare to the second argument.
e.g.

const insertData = [
{
  ...
},
  ...
]
const dbTrx = await Database.beginTransaction()
await YourModel.createMany(insertData, dbTrx)

hope its help:grinning: