Skip to content
Advertisement

Add foreign key to a migration (Laravel)

I´ve spent the whole day trying to figure out what is happening with the following migration.

This the migration of the table. My idea is to use ‘id_stays_abroad’ and ‘user_id’ as foreign keys.

    class CreateBookingStaysAbroad extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('booking__stays__abroads', function (Blueprint $table) {
            $table->bigIncrements('id');
            $table->timestamps();
            $table->unsignedInteger('id_stays_abroad')->nullable();
            $table->unsignedInteger('user_id')->nullable();
            $table->string('status')->nullable();
            $table->date('departure_date');
            $table->date('return_date');
            $table->integer('number_weeks');

        });

    }

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

This is the other migration to add the foreign keys

   class AddForeignKeyBookingStaysAbroadTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::table('booking__stays__abroads', function($table) {

            $table->foreign('id_stays_abroad')
                    ->references('id')
                    ->on('stays_abroads');

            $table->foreign('user_id')
                    ->references('id')
                    ->on('users');
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
            Schema::table('booking__stays__abroads', function (Blueprint $table) {
            $table->dropForeign('booking__stays__abroads_id_stays_abroad_foreign');
            $table->dropForeign('booking__stays__abroads_user_id_foreign');

    });
  }
}

When I run php artisan migrate I got the following error:

SQLSTATE[HY000]: General error: 1215 Cannot add foreign key constraint (SQL: alter table booking__stays__abroads add constraint booking__stays__abroads_id_stays_abroad_foreign foreign key (id_stays_abroad) references stays_abroads (id))

Thanks in advance, guys.

Advertisement

Answer

You are not using the same column definition for id and id_stays_abroad. Use unsignedBigInteger instead of unsignedInteger.

$table->unsignedBigInteger('id_stays_abroad')->nullable();
$table->unsignedBigInteger('user_id')->nullable();
User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement