How to reload a Model using Transactions?


I need to get the automatically generated UUID when a user was created during a transaction, because I need you to create your post before saving, but I’m having the following error:

E_RUNTIME_ERROR: Cannot reload model since row with id 1 has been removed


User migration

  .defaultTo(this.db.raw('uuid_generate_v4()')) // auto generate uuid


const trx = await Database.beginTransaction()

const user = await User.create({ name: 'Foo', password: 'Bar' }, trx)

await user.reload() // to get auto generated uuid, but getting error

const post = await Post.create({ user_uuid: user.uuid, post: 'Baz' }, trx)

await trx.commit()

Maybe have another option ?

Hmm, the code you shared should be working. At least looks like it should…

My guess is that transaction breaks it. Since it’s not actually written to DB it can’t query it to reload it

Maybe user.reload() accepts trx too?

Other thing to think about is that perhaps you can replace primary key (id) with (uuid). Since saves etc return primary key (if I remember correctly…)