lucid icon indicating copy to clipboard operation
lucid copied to clipboard

BeforeCreate to generate Randomuuid primarykey

Open yudha-dev opened this issue 1 year ago • 2 comments

Package version

21.3.0

Describe the bug

I tried to set a default random ID as the primary key using randomUUID, but it isn't working

export default class User extends compose(BaseModel, AuthFinder) {
  @beforeCreate()
  static assignUuid(user: User) {
    user.id = crypto.randomUUID()
  }

  @column({ isPrimary: true })
  declare id: string
}

Reproduction repo

No response

yudha-dev avatar Oct 14 '24 14:10 yudha-dev

Hey @yudha-dev! 👋🏻

Could you clarify what you mean by "it isn't working"? I've implemented this several times in my project without any issues. If you could share a reproduction of the problem, I'd be happy to help troubleshoot.

RomainLanz avatar Oct 14 '24 14:10 RomainLanz

I tried the above model and ran the seeder, but it didn’t work and said that the ID must be filled. It doesn’t create automatically; we need to define the ID first

yudha-dev avatar Oct 14 '24 14:10 yudha-dev

Try to add this to your model

static selfAssignPrimaryKey = true;

https://lucid.adonisjs.com/docs/models#selfassignprimarykey

CodingDive avatar Oct 30 '24 19:10 CodingDive

@yudha-dev As mentioned by Romain please share a reproduction repo for us to further debug the issue

thetutlage avatar Oct 31 '24 05:10 thetutlage

yes i try again and works.. thanks

yudha-dev avatar Nov 04 '24 04:11 yudha-dev