Ad

Errno: 150 "Foreign Key Constraint Is Incorrectly Formed" How Can I Fix This?

- 1 answer

I have been trying it on different ways, but i can not get the error away. so my question is: Can anyone else see the mistake is made?

this is my code:

public function up()
{
    Schema::create('users', function (Blueprint $table) {
        $table->bigIncrements('id')->unique();
        $table->boolean('admin')->default('0');
        $table->string('name');
        $table->string('email')->unique();
        $table->timestamp('email_verified_at')->nullable();
        $table->string('password');
        $table->rememberToken();
        $table->timestamps();
    });
}


public function up()
{
    Schema::create('places', function (Blueprint $table) {
        $table->bigIncrements('id')->unique();
        $table->string('location_name');
        $table->string('village');
        $table->string('street');
        $table->integer('number')->unsigned();
    });
}

public function up()
{
    Schema::create('planning', function (Blueprint $table) {
        $table->bigIncrements('id')->unique();
        $table->unsignedInteger('places_id');
        $table->time('van');
        $table->time('tot');
        $table->date('dag');
        $table->timestamps();
        $table->unsignedInteger('created_by');

        $table->foreign('places_id')
            ->references('id')
            ->on('places')
            ->onDelete('cascade');

        $table->foreign('created_by')
            ->references('id')
            ->on('users')
            ->onDelete('cascade');
    });

}

PDOException::("SQLSTATE[HY000]: General error: 1005 Can't create table `foodtruck`.`#sql-3be8_b8` (errno: 150 "Foreign key constraint is incorrectly formed" )")

I want this error message to leave my command line and my migration file to be fixed on a way i can use it normally :)

Ad

Answer

Because places_id and created_by are defined as bigIncrements, you cannot define their foriegn keys as unsignedInteger it needs to be the corresponding data type which according to the documentation is:

Auto-incrementing UNSIGNED BIGINT (primary key) equivalent column.

which is equivalent to unsignedBigInteger.

Change,

$table->unsignedInteger('places_id');
$table->unsignedInteger('created_by');

To,

$table->unsignedBigInteger('places_id');
$table->unsignedBigInteger('created_by');
Ad
source: stackoverflow.com
Ad