在Adonisjs和MySQL中生成UUID不起作用

4

我有一个问题,不太理解如何在AdonisJS中创建UUID。我的数据库使用的是MySQL。当我启动服务器并发布数据时,这个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()
    })
  }

似乎与此GitHub页面密切相关。 - Tim Biegeleisen
@TimBiegeleisen,实际上我并不是在创建数据库或使用knex,数据库已经存在了。那么,你有其他的解决方案吗? - chiper4
1个回答

7

但是你可以通过在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;

我们可以使用命令 adonis make:hook Customer 创建一个名为 CustomerHook 的钩子。

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

了解有关Adonis Hooks的更多信息,请访问此处:https://adonisjs.com/docs/4.1/database-hooks


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接