Home > Software engineering >  Foreign key constraint is incorrectly formed on Laravel
Foreign key constraint is incorrectly formed on Laravel

Time:04-08

public function up()
    {
        Schema::create('jobs', function (Blueprint $table) {
            $table->id()->autoIncrement();
            $table->unsignedBigInteger('position_id');
            $table->unsignedBigInteger('taskmaster');
            $table->Integer('task_id');
            $table->string('title',150);
            $table->string('description')->nullable();
            $table->timestamp('finished_at')->nullable();
            $table->timestamps();
            $table->foreign('position_id')->references('id')->on('positions')->onDelete('cascade');
            $table->foreign('taskmaster')->references('id')->on('users')->onDelete('cascade');
            $table->foreign('task_id')->references('id')->on('firmas')->onDelete('cascade');
        });
    }

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

I have a problem on laravel. When I add the first two foreign keys, it does not give a problem, but when I add the foreign key of the 'company' table at the bottom, it gives an error. The error is as follows:

 General error: 1005 Can't create table `advertisement`.`jobs` (errno: 150 "Foreign key constraint is incorrectly formed") (SQL: alter table `jobs` add constraint `jobs_task_id_foreign` foreign key (`task_id`) references `firmas` (`id`) on delete cascade)


CodePudding user response:

There should be the same datatype of the column in firmas table id is of type integer if not then change the code

$table->Integer('task id'); to below code.

$table-›unsignedBigInteger('task id');

CodePudding user response:

Your primary key and foreign key type must remain same. For laravel it is by default UnsignedBigInteger. So check and try each and every foreign and primary key type which must be UNSIGNED BIG INT.

Or you can try.

$table->foreignId('position_id')->constrained()->onUpdate('cascade')->onDelete('cascade');

It simply creates the position_id column contrained with positions table.

Read Here. https://laravel.com/docs/9.x/migrations#column-method-foreignId

CodePudding user response:

add unsigned() method like this..

 //make id on firmas 
    $table->id()
   //and on jobs like this
        $table->integer('task_id')->unsigned();
        $table->foreign('task_id')->references('id')->on('firmas')->onDelete('cascade');
    //or
        $table->foreignId('user_id')->constrained('firmas');

try this maybe it will help you

  • Related