在Adonisjs中生成UUID,MySQL无法正常工作

时间:2019-09-23 05:12:00

标签: mysql node.js uuid adonis.js

我在理解如何使用MySQL在数据库adonisjs中创建UUID时遇到问题。当我启动服务器并发布数据时,此id_customer输出仍处于自动增量模型中。有人可以帮我解决这个问题吗?

这是我的迁移文件中的架构代码:

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()
    })
  }

1 个答案:

答案 0 :(得分:1)

但是您可以通过在Lucid模型上添加Hook来实现。

首先,如下创建customer模式:

"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;

让我们使用cmd CustomerHook创建一个名为adonis make:hook Customer的钩子

"use strict";

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

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

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

将这些行添加到您的Customer模型中

"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;

在插入客户详细信息时,默认情况下会创建一个唯一的UUID。

在此处详细了解有关阿多尼斯钩子的信息:https://adonisjs.com/docs/4.1/database-hooks