vimuth
vimuth

Reputation: 5612

Laravel migration fails with SQLSTATE[HY000]: General error: 1215

I'm trying to add a migration with laravel. This is mi migration file.

public function up() {
    Schema::create('sl_categories', function (Blueprint $table) {
        $table->bigIncrements('id');
        $table->string('title')->nullable();
        $table->integer('user_id')->unsigned()->nullable();
        $table->foreign('user_id')->references('id')->on('users')->onDelete('cascade');
        $table->softDeletes();
        $table->timestamps();
    });

    Schema::create('sl_images', function (Blueprint $table) {
        $table->bigIncrements('id');
        $table->string('image')->nullable();
        $table->integer('sl_category_id')->unsigned()->nullable();
        $table->integer('display_order')->nullable();
        $table->softDeletes();
        $table->timestamps();
    });

    Schema::table('sl_images', function(Blueprint $table) {
        $table->foreign('sl_category_id')->references('id')->on('sl_categories')->onDelete('cascade');
    });
}

public function down() {
    Schema::dropIfExists('sl_images');
    Schema::dropIfExists('sl_categories');
}

But unfortunately I'm getting this error.

Illuminate\Database\QueryException : SQLSTATE[HY000]: General error: 1215 Cannot add foreign key constraint (SQL: alter table sl_images add constraint sl_images_sl_category_id_foreign foreign key (sl_category_id) references sl_categories (id) on delete cascade)

Upvotes: 0

Views: 33

Answers (1)

vimuth
vimuth

Reputation: 5612

Finally I found the answer. The issue is InnoDB does not permit the creation of a foreign key constraint where a column references a nonmatching column type. If simply said,

This is a big integer

$table->bigIncrements('id'); 

and this is a simple integer.,

 $table->integer('sl_category_id')->unsigned()->nullable();

So we have to change the later line to bigInteger,

$table->bigInteger('sl_category_id')->unsigned()->nullable();

I'm adding this answer in case someone else will find some use of it.

Upvotes: 0

Related Questions