首页 > 解决方案 > Laravel迁移:将外键添加到ID为字符串的同一张表中

问题描述

我正在尝试进行“类别”迁移,其中每个类别在同一个表中通过 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]:一般错误:1215 无法添加外键约束(SQL:alter tablecategories添加约束categories_parent_id_foreign外键(parent_id)引用categoriesid))

字段类型都是一样的,不知道怎么办。删除“->nullable()”没有效果。

Laravel 框架版本 6.20.7

谢谢。

标签: laravelmigrationkey

解决方案


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

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');
    });
}

推荐阅读