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

时间:2020-08-27 15:28:00

标签: laravel eloquent-relationship

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

这是代码的一部分:

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

这是类别表:

    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”外键的错误。

解决此问题

只需更改数据库/迁移的日期-例如,如果希望在发布表进行此更改之前创建类别,则进行迁移:

2020_08_06_172006_create_posts_table.php 2020_08_09_172006_create_categories_table.php

从迁移类别的更改日期 2020_08_09 ,例如 2020_ 07 _09

1 个答案:

答案 0 :(得分:1)

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

为了解决该问题,您应该在创建表categories之前创建表posts