Laravel迁移:向同一个表添加外键,其中ID是字符串

Dev*_*one 6 migration key laravel

我正在尝试进行“类别”迁移,其中每个类别通过同一个表中的 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');
    });
Run Code Online (Sandbox Code Playgroud)

但我收到下一个错误:

Illuminate\Database\QueryException : SQLSTATE[HY000]: 一般错误:1215 无法添加外键约束(SQL:alter tablecategories添加约束categories_parent_id_foreign外键 ( parent_id) 引用categories( id))

字段类型相同,我不知道该怎么办。删除“->nullable()”没有任何效果。

Laravel 框架版本 6.20.7

谢谢。

BAB*_*AFI 23

在另一次运行中添加外键约束,如下所示

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');
    });
}
Run Code Online (Sandbox Code Playgroud)

  • 这不是一个奇怪的问题,因为您试图将外键分配给一个尚不存在的表(这是类别表,在创建它时,您尝试将外键引用到尚未创建但在正在创建状态...) (2认同)