Home > other >  SQLSTATE[HY000]: General error: 1215 Cannot add foreign key constraint (SQL: alter table
SQLSTATE[HY000]: General error: 1215 Cannot add foreign key constraint (SQL: alter table

Time:09-28

i have three migrations

2022_09_20_021431_create_posts_table.php

 Schema::create('posts', function (Blueprint $table) {
        $table->increments('id');
        $table->string('title', 100);
        $table->text('body');
    });

2022_09_21_021455_create_category_posts_table.php

Schema::create('category_posts', function (Blueprint $table) {
        $table->unsignedBigInteger('category_id')->nullable();
        $table->unsignedBigInteger('post_id')->nullable();
        $table->primary(['category_id', 'post_id']);
        $table->foreign('category_id')->references('id')->on('categories')->onUpdate('cascade')->onDelete('cascade');
        $table->foreign('post_id')->references('id')->on('posts')->onUpdate('cascade')->onDelete('cascade');
    });

2022_09_28_021507_create_categories_table.php

 Schema::create('categories', function (Blueprint $table) {
        $table->increments('id');
        $table->string('name', 100);
    });

i found alotof solutions but not words with me i also made new project and still have the same error

CodePudding user response:

Categories table should be created first, before the category_posts. What you can do is you can try changing the name of the "2022_09_28_021507_create_categories_table.php" to have a date before "2022_09_21_021455_create_category_posts_table.php".

For example change it to

2022_09_20_021507_create_categories_table.php

CodePudding user response:

Foreign keys and its referencing column data type should be same

so, change the $table->increments('id'); to $table->id();

in tables 2022_09_20_021431_create_posts_table.php and 2022_09_28_021507_create_categories_table.php

  • Related