How to use transaction in hooks


#1

Hi guys, i was looking for a way to use the current transaction when executing model hooks operations.

e.g. In my controller i have the following code:

const trx = await Database.beginTransaction()

const orderItem = await OrderItem.find(1)

// before attach this items i want to update the subtotal and items quantity of the order using a hook
await orderItem.product().attach([10], null, trx)

await orderItem.save(trx)

Now in my hook i have the following code

OrderItemHook.updateSubtotal = async model => {
    let product = await Product.find(model.product_id)
    model.subtotal = model.quantity * product.price
}

So, when i save my OrderItem model, it’ll have the subtotal property updated ever.

But, now, i need to update the parent order total too, and i dont know how to do this when using transactions.

My hook code now, looks like this, but it doesn’t work because of the transaction.

OrderItemHook.updateSubtotal = async model => {
    let order = await Order.find(model.order_id)
    order.total -= model.subtotal
    let product = await Product.find(model.product_id)
    model.subtotal = model.quantity * product.price
    order.total += model.subtotal
    await order.save()
    
}

#2

Not sure it’s poissible because I cannot see a way to pass the transaction (trx) to the hook.


#3

Yeah. I believe we should stick the trx on the model instance for it to be used within the hooks.