How to do query inside transaction after initialized


#1

Hello guys.

First of all, thanks a lof for adonisjs. I’m trying it on my first project and looks awesome.

I’m trying execute a query inside transaction, but did not working, be going to timeout and not return nothing.

The code’s here:

const coupon_data = request.only(['code', 'discount', 'valid_from', 'valid_until', 'quantity', 'type', 'recursive'])
const { products } = request.only(['products']);
const transaction = await Database.beginTransaction();
const coupon = await Coupon.create(coupon_data, transaction);

for (let product_id of products) {
  const product = await Product.findOrFail(product_id);  // It's here, long time executing and not return
  if (product instanceof Product) {
    await coupon.products().attach([product.id], null, transaction);
  }
}

My solution is here:

const coupon_data = request.only(['code', 'discount', 'valid_from', 'valid_until', 'quantity', 'type', 'recursive'])
const { products } = request.only(['products']);
let products_data = []

for (let product_id of products) {
  const product = await Product.findOrFail(product_id)
  if (product instanceof Product) {
    products_data.push(product.id)
  }
}

const transaction = await Database.beginTransaction();
const coupon = await Coupon.create(coupon_data, transaction);
await coupon.products().attach(products_data, null, transaction)

However, for me it’s not fine, it’s annoying because I still can not execute my query within the transaction.


#2

Try using the transaction for example;

Product.query().transacting(transaction).where('id',product_id).first()

else

Product.findOrFail(product_id, transaction)

Not tested either.

Good luck.


#3

Thanks,

That solved!!

But could also work otherwise - I had also tried it earlier, but it did not work.