【发布时间】:2021-05-08 01:01:52
【问题描述】:
我的 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 "外键约束为 格式不正确") (SQL: alter tablecategoriesadd constraintcategories_parent_id_foreign外键 (parent_id) 引用categories(id) 删除级联)
但我在类似的项目中有它,但有 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 让它工作呢?
【问题讨论】:
-
你需要在你的模型上定义主键
public $incrementing = false; protected $keyType = 'string'; -
我没有模型,只是迁移