How to get into the model pk that is generated in the database?

(pk) UUIDs are generated in the database. migration:

class CatSchema extends Schema {
  up () {
    this.createExtensionIfNotExists('uuid-ossp');
    this.createExtensionIfNotExists('pgcrypto');

    this.create('cats', (table) => {
      table.uuid('id')
        .primary()
        .unique()
        .defaultTo(this.db.raw('public.gen_random_uuid()'))
      table.string('name')
      table.timestamps()
    })
  }

how to get an id in a model?
controller:

'use strict'
const Cat=use('App/Models/Cat')

class CatController {
  index(){
    return Cat.all()
  }
  async store({request}) {
    const name = request.input('name')
    const cat = await Cat.create({name});
    return cat.id
//there is no id here, but there is one in the database
  }
}
module.exports = CatController
1 Like

Hello @lDaurenl
what have you tried so far?

I don’t know if it works, but have you tried something like this?

to select first the uuid from database and then use it on your create method

await Database.select('uuid_generate_v4() as uuid')

HelIo @melokki, i get it only with crutches.A friend advised me to do the generation in the database, and everything works fine for him.

I changed the increment to true and it worked

1 Like