0

I'm trying to figure out how migrations in Laravel work. Here you can see I'm creating 2 tables. And in the second table (RealNationalLeague), I'm having foreign keys to two columns (real_nation_id, level) in the first table (RealNationalLeagueLevel).

public function up()
    {

        ...

        Schema::create(Model\RealNationalLeagueLevel::TABLE, function (Blueprint $table) {
            $table->unsignedInteger("real_nation_id");
            $table->unsignedTinyInteger("level");

            $table->foreign("real_nation_id")->references("id")->on(Model\RealNation::TABLE);
            $table->primary(["real_nation_id", "level"]);
        });


        Schema::create(Model\RealNationalLeague::TABLE, function (Blueprint $table) {
            $table->increments("id");
            $table->unsignedInteger("real_nation_id");
            $table->unsignedTinyInteger("level");
            $table->string("name", 32);

            $table->foreign("real_nation_id")->references("real_nation_id")->on(Model\RealNationalLeagueLevel::TABLE); // this works
            $table->foreign("level")->references("level")->on(Model\RealNationalLeagueLevel::TABLE); // this does not
        });
    }

Running the migration does not work. It throws QueryException:

SQLSTATE[HY000]: General error: 1005 Can't create table `testdb`.`#sql-17a00_448a37` (errno: 150 "Foreign key constraint is incorrectly formed") (SQL: alter table `real_national_league` add constraint `real_national_league_level_foreign` foreign key (`level`) references `real_national_league_level` (`level`))

Any idea why it's not working? Thanks for any help.

P.N.
  • 341
  • 3
  • 16

1 Answers1

0

The table that you want to reference, you have to create it first, then in another migration, create a column from this table to that reference table.