Ad
Laravel Migration: Errno: 150 "Foreign Key Constraint Is Incorrectly Formed"
I receive the error
SQLSTATE[HY000]: General error: 1005 Can't create table
posys.
#sql-2b94_d2(errno: 150 "Foreign key constraint is incorrectly formed") (SQL: alter table
purchase_ordersadd constraint
purchase_orders_status_id_foreignforeign key (
status_id) references
statuses(
id))
When running my migration.
Here are my migrations:
<?php
use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class CreateStaffTable extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create('staff', function (Blueprint $table) {
$table->bigIncrements('id');
$table->string('name')->unique();
$table->string('position')->nullable();
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::dropIfExists('staff');
}
}
And
<?php
use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class CreatePurchaseOrdersTable extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create('purchase_orders', function (Blueprint $table) {
$table->bigIncrements('id');
$table->float('total_price_ex_vat', 12, 2);
$table->float('total_price_inc_vat', 12, 2);
$table->string('deliver_to');
$table->unsignedBigInteger('staff_id'); // Foreign key
$table->foreign('staff_id')->references('id')->on('staff');
$table->unsignedBigInteger('supplier_id'); // Foreign key
$table->foreign('supplier_id')->references('id')->on('suppliers');
$table->unsignedBigInteger('status_id'); // Foreign key
$table->foreign('status_id')->references('id')->on('statuses');
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::dropIfExists('purchase_orders');
}
}
Ad
Answer
To avoid error 150, pick one:
- Rearrange the order of
CREATE TABLEs
DISABLE
FKs, do the creates, enable them.- Don't
ADD
the FKs until all theCREATEs
have been done.
Ad
source: stackoverflow.com
Related Questions
- → "failed to open stream" error when executing "migrate:make"
- → I can't do a foreign key, constraint error
- → Setting a default value on settings form return null in Octobercms
- → Eloquent Multitable query
- → "Laravel 5.1" add user and project with userId
- → Image does not go in database with file name only tmp name saved?
- → Database backup with custom code in laravel 5 and get the data upto 10 rows from per table in database
- → Trait 'IlluminateFoundationBusDispatchesJobs' not found
- → Setting the maxlength of text in an element that is displayed
- → laravel check between 2 integer from database
- → how to retrieve image from database in laravel 5.1?
- → relationship for database Column type object
- → Carousel in Laravel 4 does not show as expected
Ad