Laravel 迁移:将外键添加到相同的 table 其中 ID 是一个字符串
Laravel migration: adding foreign key to the same table where ID is a string
我正在尝试进行“类别”迁移,其中每个类别在同一 table 中通过 ID 引用它的父类别。
迁移:
Schema::create('categories', function (Blueprint $table) {
$table->string('id', 36)->primary();
$table->string('parent_id', 36)->nullable();
$table->foreign('parent_id')->references('id')->on('categories');
$table->string('name');
});
但我遇到下一个错误:
Illuminate\Database\QueryException : SQLSTATE[HY000]: General error: 1215 Cannot add foreign key constraint (SQL: alter table categories
add constraint categories_parent_id_foreign
foreign key (parent_id
) references categories
(id
))
字段类型相同,我不知道该怎么办。
删除“->nullable()”没有任何效果。
Laravel 框架版本 6.20.7
谢谢。
在另一个运行中添加外键约束,如下所示
public function up()
{
Schema::create('categories', function (Blueprint $table) {
$table->string('id', 36)->primary();
$table->string('parent_id', 36)->nullable();
$table->string('name');
});
Schema::table('categories',function (Blueprint $table){
$table->foreign('parent_id')->references('id')->on('categories');
});
}
我正在尝试进行“类别”迁移,其中每个类别在同一 table 中通过 ID 引用它的父类别。
迁移:
Schema::create('categories', function (Blueprint $table) {
$table->string('id', 36)->primary();
$table->string('parent_id', 36)->nullable();
$table->foreign('parent_id')->references('id')->on('categories');
$table->string('name');
});
但我遇到下一个错误:
Illuminate\Database\QueryException : SQLSTATE[HY000]: General error: 1215 Cannot add foreign key constraint (SQL: alter table
categories
add constraintcategories_parent_id_foreign
foreign key (parent_id
) referencescategories
(id
))
字段类型相同,我不知道该怎么办。 删除“->nullable()”没有任何效果。
Laravel 框架版本 6.20.7
谢谢。
在另一个运行中添加外键约束,如下所示
public function up()
{
Schema::create('categories', function (Blueprint $table) {
$table->string('id', 36)->primary();
$table->string('parent_id', 36)->nullable();
$table->string('name');
});
Schema::table('categories',function (Blueprint $table){
$table->foreign('parent_id')->references('id')->on('categories');
});
}