Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Generate UUID in Adonisjs and MySQL isn't working

i have a problem to understand how to create UUID in adonisjs, my database using MySQL. When i'm start server and post data, this id_customer output still in auto-increment model. Anyone can help me how to solving this problem?

This is schema code in my migration file:

async up () {
    await this.db.raw('CREATE EXTENSION IF NOT EXISTS "uuid-ossp";')
  }
  up () {
    this.create('customers', (table) => {
      table.increments()
      table.uuid('id_customer').primary().defaultTo(this.db.raw('uuid_generate_v4()'))
      table.timestamps()
    })
  }
like image 344
chiper4 Avatar asked Mar 04 '23 09:03

chiper4


1 Answers

But you can achieve this by adding Hook on your Lucid model.

First, create customer schema as follows:

"use strict";

const Schema = use("Schema");

class Customer extends Schema {
  up() {
    this.create("customers", table => {
      table.uuid("id").primary();

      // Rest of your schema
    });
  }

  down() {
    this.drop("customers");
  }
}

module.exports = Customer;

Let's create a hook called CustomerHook using cmd adonis make:hook Customer

"use strict";

const uuidv4 = require("uuid/v4");

const CustomerHook = (exports = module.exports = {});

CustomerHook.uuid = async customer => {
  customer.id = uuidv4();
};

Add these lines on your Customer model

"use strict";

const Model = use("Model");

class Customer extends Model {
  static boot() {
    super.boot();
    this.addHook("beforeCreate", "CustomerHook.uuid");
  }

  static get primaryKey() {
    return "id";
  }

  static get incrementing() {
    return false;
  }

  // Rest of the model
}

module.exports = Customer;

While inserting customer details a unique UUID will be created by default.

Read more about adonis hook here: https://adonisjs.com/docs/4.1/database-hooks

like image 153
Rajeev Radhakrishnan Avatar answered Mar 06 '23 21:03

Rajeev Radhakrishnan