Laravel 5: Foreign key constraint is incorrectly formed

0

I'm trying to create the following two tables with Laravel:

Schema::create('orders', function (Blueprint $table) {
   $table->bigIncrements('id');
   $table->primary('id');
   $table->bigInteger('numPedido')->unsigned();
   $table->string('name', 300);
   $table->string('business', 300)->nullable();
   $table->string('dni', 20);
   $table->string('phone', 20);
   $table->string('address', 300);
   $table->string('cp', 10);
   $table->string('town', 100);
   $table->string('city', 100);
   $table->string('email', 300);
   $table->timestamps();
});

Schema::create('order_items', function (Blueprint $table) {
   $table->bigIncrements('id'); 
   $table->primary('id');
   $table->bigInteger('order_numPedido')->unsigned();
   $table->foreign('order_numPedido')
         ->references('numPedido')
         ->on('orders')
         ->onDelete('cascade');
   $table->string('name', 300);
   $table->string('quantity', 5);
   $table->string('import', 10);
});

But it generates the following error:

General error: 1005 Can't create table 'orders' (errno: 150 "Foreign key constraint is incorrectly formed")

I can not find the problem. Thank you very much.

    
asked by Sergio López 21.09.2017 в 14:20
source

2 answers

0

The error is due to a conflict with the primary key.

You do not need to add the $table->primary('id'); lines. When you set the column id with $table->bigIncrements('id'); is already set as primary key.

You can see more information about it in the official documentation: link

    
answered by 21.09.2017 / 16:51
source
0

When creating the migrations, remember that you must first create the table / model to which you are going to relate.

php artisan make:model Order -m 
php artisan make:model Order-item -m 
    
answered by 11.01.2018 в 03:51