Home > Software engineering >  Laravel 9.X.X error when trying to add foreign key with 'php artisan migrate'
Laravel 9.X.X error when trying to add foreign key with 'php artisan migrate'

Time:12-16

I keep getting the same error when running 'php artisan migrate'.

SQLSTATE[HY000]: General error: 1005 Can't create table dawteste.utilizador (errno: 150 "Foreign key constraint is incorrectly formed") (SQL: alter table utilizador add constraint utilizador_tipo_utilizador_id_foreign fore ign key (tipo_utilizador_id) references tipo_utilizador (id))

Why does it write utilizador_tipo_utilizador_id_foreign instead of utilizador.tipo_utilizador_id or just tipo_utilizador_id?

Is this simply a syntax error on the query?

Utilizador Table

Tipo Utilizador Table

Terminal Error

return new class extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('utilizador', function (Blueprint $table) {
            $table->id();
            $table->integer('tipo_utilizador_id')->unsigned();
            $table->foreign('tipo_utilizador_id')->references('id')->on('tipo_utilizador');
            $table->string('name');
            $table->string('email')->unique();
            $table->timestamp('email_verified_at')->nullable();
            $table->string('password');
            $table->rememberToken();
            $table->timestamps();
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::dropIfExists('users');
    }
};
return new class extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('tipo_utilizador', function (Blueprint $table) {
            $table->id();
            $table->string('descricao');
            $table->timestamps();
        });
    }

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

CodePudding user response:

utilizador_tipo_utilizador_id_foreign is the name/key of the constraint applied between the foreign key tipo_utilizador_id and the referenced key tipo_utilizador.id. nothing wrong with the naming.

Your foreign key doesn't have the right type of field, it need to be an unsigned big integer.

Schema::create('utilizador', function (Blueprint $table) {
    $table->id();
    $table->bigInteger('tipo_utilizador_id')->unsigned();
    $table->foreign('tipo_utilizador_id')->references('id')->on('tipo_utilizador');
    $table->string('name');
    $table->string('email')->unique();
    $table->timestamp('email_verified_at')->nullable();
    $table->string('password');
    $table->rememberToken();
    $table->timestamps();
});
  • Related