0

I have this error:

PDOException::("SQLSTATE[HY000]: General error: 1005 Can't create table shreemad.posts (errno: 150 "Foreign key constraint is incorrectly formed")")

Table 1:

public function up()
{
    Schema::create('category', function (Blueprint $table) {
        $table->bigIncrements('id');
        $table->unsignedInteger('type_id');
        $table->string('product_type');
        $table->timestamps();
    });
}

Table:

public function up()
{
    Schema::create('posts', function (Blueprint $table) {
        $table->bigIncrements('id');
        $table->unsignedInteger('type');
        $table->foreign('type')->references('type_id')->on('category');
        $table->string('title');
        $table->string('description');
        $table->integer('price')->nullable();
        $table->mediumtext('image')->nullable();
        $table->timestamps();
    });
}
Al Foиce ѫ
  • 4,195
  • 12
  • 39
  • 49
rajhem
  • 1
  • 1
  • Does this answer your question? [mysql Foreign key constraint is incorrectly formed error](https://stackoverflow.com/questions/8434518/mysql-foreign-key-constraint-is-incorrectly-formed-error) – Gary Thomas Feb 25 '20 at 08:14
  • The reference must be the primary key of the category table. And at it's id. $table->foreign('type')->references('id')->on('category'); – Berthol Yvano Feb 25 '20 at 09:59
  • You have to include an onDelete and on Update method on your foreign key field. And also if that does not do it check for how order of your migrations.the category migrations should be before the posts migrations. – Patrick Obafemi Feb 25 '20 at 12:28
  • Make sure that you have a proper order of your migrations, like first category and then posts. Order matters – Akhtar Munir Feb 25 '20 at 12:49

1 Answers1

0

You have to include an onDelete and on Update method on your foreign key field.

    $table->unsignedBigInteger('type');
    $table->foreign('type')->references('type_id')->on('category')->onDelete('cascade')->onUpdate('cascade');

And also if that does not do it check for how order of your migrations.the category migrations should be before the posts migrations.

Patrick Obafemi
  • 908
  • 2
  • 20
  • 42