LARAVEL 5.5 Foreign key constraint is incorrectly formed'

2.3k views Asked by At

I am encountering "errno: 150 'Foreign key constraint is incorrectly formed'" when migrating.

I have a table that needs 3 foreign keys:

  Schema::create('ads', function (Blueprint $table) {
        $table->increments('id');
        $table->string('prodname');
        $table->string('mfrname');
        $table->decimal('priceam');
        $table->string('imagenametxt',500);
        $table->string('specstxt',500);
        $table->string('otherinfotxt',500);
        $table->decimal('avalableqty');
        $table->binary('validyn');
        $table->binary('checkyn');
        $table->binary('updatedyn');
        $table->integer('selleridno')->unsigned();
        $table->integer('catidno')->unsigned();
        $table->integer('subcatidno')->unsigned();
        $table->timestamps();

    });

    Schema::table('ads', function(Blueprint $table){
        $table->foreign('selleridno')->references('id')->on('users');
        $table->foreign('catidno')->references('id')->on('categories');
        $table->foreign('subcatidno')->references('id')-> 
         on('subcategories');
    });

Users, Categories and Subcategories table are created before this table. selleridno and catidno was successfully created but in creating foreign key for subcatidno I am encountering the error. any suggestions/opinions? thank you in advance.

My Database is MySql.

Just in case you need the SubCategories table here it is:

Schema::create('sub_categories', function (Blueprint $table) {
            $table->increments('id');
            $table->string('subcategorycd');
            $table->string('subcategorytxt');
            $table->integer('categoryidno')->unsigned();
            $table->timestamps();

            $table->foreign('categoryidno')->references('id')->on('categories');
        });
2

There are 2 answers

0
Don't Panic On BEST ANSWER

This foreign key is on a table called subcategories:

$table->foreign('subcatidno')->references('id')->on('subcategories');

But your table is actually called sub_categories:

Schema::create('sub_categories', function (Blueprint $table) {
0
mafortis On

When you get subcategory you don't need to get category as well because you get category in subcategory migrate.

And also try to get them as user_id and subcategory_id instead of selleridno and subcatindo.

See if it works.

PS: your subcategory creat method has issue separate foregin key just like you did for ads.

Schema::table('subcategory', function(Blueprint $table){ 

    $table->foreign('category')->references('id')-> on('categories'); 
});