user9277589
user9277589

Reputation:

SQLSTATE[HY000]: General error: 1215 Cannot add foreign key constraint - Laravel

I'm trying to create a table to hold photos and link it to the ad (property id). I'm getting this error

SQLSTATE[HY000]: General error: 1215 Cannot add foreign key constraint

These are my migration files

2018_02_14_191609_create_property_adverts_table

<?php

use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;

class CreatePropertyAdvertsTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('property_adverts', function (Blueprint $table) {
            $table->increments('id');
            $table->string('address');
            $table->string('county');
            $table->string('town');
            $table->string('type');
            $table->string('rent');
            $table->string('date');
            $table->string('bedrooms');
            $table->string('bathrooms');
            $table->string('furnished');
            $table->longText('description');
            $table->timestamps();
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::dropIfExists('property_adverts');
    }
}

2018_02_18_165845_create_property_advert_photos_table

<?php

use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;

class CreatePropertyAdvertPhotosTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('property_advert_photos', function (Blueprint $table) {
            $table->increments('id');
            $table->integer('propertyadvert_id')->nullable();
            $table->foreign('propertyadvert_id')->references('id')->on('property_adverts');
            $table->timestamps();
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::dropIfExists('property_advert_photos');
    }
}

So the

Upvotes: 1

Views: 460

Answers (1)

Alexey Mezenin
Alexey Mezenin

Reputation: 163768

Make it unsigned because you're using increments(). And move FK constraint part to a separate closure:

public function up()
{
    Schema::create('property_advert_photos', function (Blueprint $table) {
        $table->increments('id');
        $table->unsignedInteger('propertyadvert_id')->nullable();
        $table->timestamps();
    });

    Schema::table('property_advert_photos', function (Blueprint $table) {
        $table->foreign('propertyadvert_id')->references('id')->on('property_adverts');
    });
}

Upvotes: 3

Related Questions