"Foreign key constraint is incorrectly formed" on Laravel

Viewed 69

I'm trying to create a new table for my database.

I previously created a table (tipo) with a PK (IdCorso), then another table(corsoscii) with a foreign key associated with tipo.
When I execute the artisan command for corsoscii
php artisan migrate --path='./database/migrations/2021_02_23_155544_create_corsoscii_table.php' it gives me this error:

("SQLSTATE[HY000]: General error: 1005 Can't create table impianto_scii.corsoscii (errno: 150 "Foreign key constraint is incorrectly formed")")

This is the setup code for "tipo"

public function up()
    {
        Schema::create('tipo', function (Blueprint $table) {
            $table->increments('idCorso');
            $table->string('descrizione');
            $table->timestamps();
        });
    }

...and for "corsoscii"

  public function up()
{
    Schema::create('corsoscii', function (Blueprint $table) {
        $table->increments('idCorso');
        $table->integer('tipo');
        $table->string('nome');
        $table->integer('membriMax');
        $table->date('inizio');
        $table->date('fine');
        $table->timestamps();

    });

    Schema::table('corsoscii', function(Blueprint $table){

        $table->foreign('tipo')
            ->references('idCorso')->on('tipo')
            ->onDelete('cascade');
        
        $table->primary('idCorso');
    });
}

I'm a neophyte with Laravel, any advice is welcome.

2 Answers

$table->integer('tipo'); needs to match exactly the field it is a foreign key for.

$table->increments('idCorso'); generates an unsignedInteger, so that's what it should be.

$table->unsignedInteger('tipo');

If your migration uses bigIncrements, you need to use:

$table->unsignedBigInteger('tipo');

first please run

php artisan migrate:rollback

then delete "corsoscii" table. then try these changes.

Schema::create('corsoscii', function (Blueprint $table) {
            $table->increments('idCorso');
            $table->integer('tipo')->unsigned();;
            $table->string('nome');
            $table->integer('membriMax');
            $table->date('inizio');
            $table->date('fine');
            $table->timestamps();

        });

        Schema::table('corsoscii', function(Blueprint $table){

            $table->foreign('tipo')
                  ->references('idCorso')->on('tipo')
                  ->onDelete('cascade');
        });

first try unsigned() for tipo and then idCorso is already primary key when you will use increments() method. then run

php artisan migrate

this will work fine. i tried that.

Related