bch*_*378 3 mysql uuid node.js adonis.js
我有一个问题要理解如何在 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()
})
}
Run Code Online (Sandbox Code Playgroud)
但是您可以通过在 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;
Run Code Online (Sandbox Code Playgroud)
让我们创建一个CustomerHook使用 cmd调用的钩子adonis make:hook Customer
"use strict";
const uuidv4 = require("uuid/v4");
const CustomerHook = (exports = module.exports = {});
CustomerHook.uuid = async customer => {
customer.id = uuidv4();
};
Run Code Online (Sandbox Code Playgroud)
在您的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;
Run Code Online (Sandbox Code Playgroud)
在插入客户详细信息时,默认情况下将创建一个唯一的 UUID。
在此处阅读有关 adonis 钩子的更多信息:https ://adonisjs.com/docs/4.1/database-hooks
| 归档时间: |
|
| 查看次数: |
2867 次 |
| 最近记录: |