How to save data in afterCreate model hook?

I use afterCreate hook because generates a unique code base on creating data id.
first, get id in afterCreate hook.

models file

this.addHook("afterCreate", async instance => {
      let branch = "00";
      const type = "AF";
      const id = instance.id;
      let code = type + branch + "0";
      let codeformate = "";
      if (id.toString().length < 3) {
        codeformate = code + "0".repeat(3 - id.toString().length) + id;
      } else {
        codeformate = code + id;
      }
       instance.code = codeformate
      instance.save()    
  });

instance.save() one time store code ,
after all record have code value null

when use below

instance.code = codeformate
await instance.save()

then code not store

1 Like

‘use strict’

const XHook = exports = module.exports = {}

XHook.setReferenceId = async (x) => {
console.log(“After Created”, x)
x.r_id = x.id
await x.save()
}
Not Updated

const trx = await Database.beginTransaction();

Change
x.save(trx) => x.save() // In creating