Laravel 外键约束的格式不正确(errno 150)

Laravel foreign key constraint is incorrectly formed (errno 150)

有人能告诉我为什么我得到的外键格式不正确吗?

部分代码如下:

    public function up()
    {
        Schema::create('posts', function (Blueprint $table) {
            $table->id();
            $table->foreignId('user_id')->constrained()->onDelete('cascade');
            $table->string('title');
            $table->text('content');
            $table->string('featured');
            $table->string('slug');
            $table->foreignId('category_id')->constrained()->onDelete('cascade');

            $table->softDeletes();
            $table->timestamps();
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::dropIfExists('posts');
    }

这是类别 table:

    public function up()
    {
        Schema::create('categories', function (Blueprint $table) {
            $table->id();
            $table->string('name');
            $table->string('slug');
            $table->timestamps();
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::dropIfExists('categories');
    }

备注

它不会为 'user_id' 仅针对类别的外键删除此错误。

修复此问题

只需更改 database/migrations 上的日期 - 例如迁移,如果您希望在发布帖子之前创建类别 table,请执行此更改:

2020_08_06_172006_create_posts_table.php 2020_08_09_172006_create_categories_table.php

更改类别迁移的日期 2020_08_09 例如 2020_07_09

我猜你的 table posts 是在 categories
之前创建的 因此,您不能将 posts.category_id 约束到 categories.id table.

为了解决这个问题,您应该在创建 table posts

之前创建 table categories