最新消息: 电脑我帮您提供丰富的电脑知识,编程学习,软件下载,win7系统下载。

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

IT培训 admin 5浏览 0评论

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

我在了解如何使用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()
    })
  }
回答如下:

但是您可以通过在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/docs/4.1/database-hooks

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

我在了解如何使用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()
    })
  }
回答如下:

但是您可以通过在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/docs/4.1/database-hooks

发布评论

评论列表 (0)

  1. 暂无评论