adonisjs / lucid

AdonisJS SQL ORM. Supports PostgreSQL, MySQL, MSSQL, Redshift, SQLite and many more
https://lucid.adonisjs.com/
MIT License
1.08k stars 195 forks source link

BeforeCreate to generate Randomuuid primarykey #1059

Closed yudha-dev closed 3 weeks ago

yudha-dev commented 1 month ago

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

RomainLanz commented 1 month ago

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.

yudha-dev commented 1 month ago

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

CodingDive commented 3 weeks ago

Try to add this to your model

static selfAssignPrimaryKey = true;

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

thetutlage commented 3 weeks ago

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

yudha-dev commented 2 weeks ago

yes i try again and works.. thanks