laravel errno:150“外键约束格式错误

时间:2019-04-29 08:07:56

标签: laravel laravel-5 eloquent foreign-keys

我为laravel类别提供了以下教程:

Laravel categories with dynamic deep paths

我使用以下代码进行迁移的相同教程:

public function up()
    {
        Schema::create('categories', function (Blueprint $table) {
            $table->bigIncrements('id');
            $table->string('title');
            $table->string('slug');
            $table->integer('parent_id')->unsigned()->default(0);
            $table->timestamps();
        });

        Schema::table('categories', function (Blueprint $table) {
            $table->foreign('parent_id')->references('id')->on('categories')->onUpdate('cascade')->onDelete('cascade');
        });

    }

但我有以下错误:

SQLSTATE[HY000]: General error: 1005 Can't create table 'xxx'.'#sql-453_147' (errno: 150 "Foreign key constraint is incorrectly formed")
(SQL: alter table 'categories' add constraint 'categories_parent_id_foreign' foreign key ('parent_id') references 'categories' ('id') on delete cascade on update cascade)

感谢帮助

2 个答案:

答案 0 :(得分:1)

在Laravel中创建新表时。将会生成迁移,例如:

$table->bigIncrements('id');

代替(在较早的Laravel版本中):

$table->increments('id');

使用bigIncrements时,外键需要bigInteger而不是整数。因此您的代码将如下所示:

public function up()
    {
        Schema::create('categories', function (Blueprint $table) {
            $table->bigIncrements('id');
            $table->string('title');
            $table->string('slug');
            $table->bigInteger('parent_id')->unsigned()->default(0);
            $table->timestamps();
        });

        Schema::table('categories', function (Blueprint $table) {
            $table->foreign('parent_id')->references('id')->on('categories')->onUpdate('cascade')->onDelete('cascade');
        });

    }

答案 1 :(得分:0)

问题是由于列类型的不同。因此,与本教程不同,您使用的是bigIncrements,这意味着ID为大整数,而parent_id使用默认的整数。尝试将id更改为此:

$table->increments('id');

或您的parent_id

$table->bigInteger('parent_id')->unsigned()->default(0);