我在理解如何使用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()
})
}
答案 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