Lucid: beforeUpdate hook not getting called

Created on 9 May 2018  路  5Comments  路  Source: adonisjs/lucid

beforeUpdate is not executing the hook when called adonis version 4

paydirect
this is my controller

paydirectmodel
this is my model

paydirecthook
and this is my hook

the beforeCreate works fine with the same hook but does not work for beforeUpdate
and the update insert successfully without harshing or sending sms

Most helpful comment

Nope, it has nothing to do with how many fields gets updated. So this is what you need to understand.

When beforeUpdate hook is called, it given the values of the current row, right?

this.addHook('beforeUpdate', function (modelInstance) {
  modelInstance.id
})

When you perform a direct update using the query builder update method, Lucid doesn't have any data about that row.

So what you need is to select the row first and then update it.

const post = await PayDirect.find(parseInt(post.pid))
post.token = token

await post.save()

All 5 comments

Hooks are not executed for bulk updates. Also there is no data to be passed to your hook, since you are just executing the update query.

Hooks works with model instances, where Lucid knows the value for a row before hand.

thanks @thetutlage so what is the best way to execute the hook on update, will it work successfully with a single field update?
as in

const deposit = await PayDirect.query() .where('id', parseInt(post.pid)) .update({ token: token })

Nope, it has nothing to do with how many fields gets updated. So this is what you need to understand.

When beforeUpdate hook is called, it given the values of the current row, right?

this.addHook('beforeUpdate', function (modelInstance) {
  modelInstance.id
})

When you perform a direct update using the query builder update method, Lucid doesn't have any data about that row.

So what you need is to select the row first and then update it.

const post = await PayDirect.find(parseInt(post.pid))
post.token = token

await post.save()

OK I will do just this and report

thanks @thetutlage this soluction fixes my problem and other similar ones
i will now have to close the issue

Was this page helpful?
0 / 5 - 0 ratings

Related issues

SAGV picture SAGV  路  7Comments

yariksav picture yariksav  路  7Comments

ghost picture ghost  路  3Comments

moar55 picture moar55  路  4Comments

hectorgrecco picture hectorgrecco  路  3Comments