Error 1215 with foreign key

Asked

Viewed 20 times

-1

I am working my first relationship of one to one tables in Laravel for countries and locations, created the models and migrate them to the two tables.

Country table:

public function up()
{
    Schema::create('countries', function (Blueprint $table) {
        $table->id();
        $table->string('name')->unique();
        $table->timestamps();
    });
}

And the table of locations:

public function up()
{
    Schema::create('locations', function (Blueprint $table) {
        $table->id();
        $table->integer('country_id')->unsigned();
        $table->integer('latitude');
        $table->integer('longitude');
        $table->timestamps();
        $table->foreign('country_id')
                ->references('id')
                ->on('countries')
                ->onDelete('cascade');
    });
}

I executed the command php artisan migrate to import tables into the database:

inserir a descrição da imagem aqui

What is returned is the erro 1215, I opened phpMyAdmin and went to the database designer and checked that the relationship was not really created:

inserir a descrição da imagem aqui

I went back to the migrate up() function and set the field size to 20 characters to see if this was the problem and ran the command php artisan migrate and the error persisted.

1 answer

0


I was able to circumvent the error by changing the migrate Locations instructions to:

public function up()
{
    Schema::create('locations', function (Blueprint $table) {
        $table->bigIncrements('id');
        $table->unsignedBigInteger('country_id');
        $table->integer('latitude');
        $table->integer('longitude');
        $table->timestamps();
        $table->foreign('country_id')
                ->references('id')
                ->on('countries')
                ->onDelete('cascade');
    });
}
  • Exactly, the guys in the columns didn’t match.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.