php - Laravel 与 UUID 的同表关系
问题描述
我的 Laravel 迁移有一些问题。我正在尝试从同一个表中添加可为空的父键。像这样:
Schema::create('categories', function (Blueprint $table) {
$table->uuid('id')->primary();
$table->string('name');
$table->uuid('parent_id')->nullable();
$table->foreign('parent_id')->references('id')->on('categories')->onDelete('cascade');
$table->timestamps();
});
它总是回来
SQLSTATE[HY000]:一般错误:1005 无法创建表
ecommerce
。categories
(errno: 150 "Foreign key constraint is wrongly forms") (SQL: alter tablecategories
add constraintcategories_parent_id_foreign
foreign key (parent_id
) referencescategories
(id
) on delete cascade)
但我在类似的项目中有它,但有 id,它的工作原理是这样的:
Schema::create('categories', function (Blueprint $table) {
$table->id();
$table->unsignedBigInteger('parent_id')->nullable();
$table->string('name');
$table->timestamps();
$table->foreign('parent_id')->references('id')->on('categories');
});
但是如何使它与 uuid 一起工作呢?
解决方案
在第一次迁移创建categories
表后,在第二次迁移定义外键,如下所示:
public function up()
{
Schema::create('categories', function (Blueprint $table) {
$table->uuid('id')->primary();
$table->string('name');
$table->uuid('parent_id')->nullable();
$table->timestamps();
});
Schema::table('categories', function (Blueprint $table) {
$table->foreign('parent_id')->references('id')->on('categories')->onDelete('cascade');
});
}
上面的代码用Laravel 8.25.0
&测试MariaDB 10.4.14
推荐阅读
- javascript - 循环生成空列表
- mysql - 设置 lower_case_table_names=0 时如何解决 Can't connect to MySQL server on 'localhost' (10061)?
- php - cURL Paypal Identity API 响应提供商家信息,而不是付款人
- codeigniter - 使用 Codeigniter 将日期输入值从视图传递到控制器
- microsoft-teams - 有效域不能使用隧道站点
- c - 如何从 C 中的 char 数组中获取单个单词?
- python-3.x - 生成列表中所有可能的项目组合并将它们存储在不同的列表中,并在以后访问它们。我在下面举了一个例子
- python - Python将字典元组列表转换为数据框
- java - 使用 java replace 方法替换字符串中的字符
- java - Spring JPA 中的 SQL 聚合 GROUP BY 和 COUNT