anchan42's avatar

Create foreign key on tiny interger

How could create a foreign key with tiny integer? This is what I have tried, but the migration still saying that the data type is incompatible.

    Schema::create('equipment_types', function (Blueprint $table) {
        $table->tinyIncrements('id');
        $table->string('description');
        $table->timestamps();
    });

and then this on the other table,

    Schema::create('equipment', function (Blueprint $table) {
        $table->id();
        $table->timestamps();
        $table->string('description');
        
        $table->tinyInteger('equipment_type_id')->unsigned();
        $table->foreign('equipment_type_id')->references('id')->on('equipment')->onUpdate('cascade');

    });
0 likes
5 replies
Rebwar's avatar
Rebwar
Best Answer
Level 32

in equipments table; change below line:

$table->foreign('equipment_type_id')->references('id')->on('equipment')->onUpdate('cascade');

to:

$table->foreign('equipment_type_id')->references('id')->on('equipment_types')->onUpdate('cascade');
1 like
tisuchi's avatar

@anchan42 I believe @rebwar answer should work.

Just to explain his answer, the foreign key should reference the primary key of the other table, not the same table.

1 like
anchan42's avatar

Oh my gosh, how could I be so stupid and missed that. It works like charm. Thanks a lot 👍

kokoshneta's avatar

@anchan42 You can use the “Set Best Answer” button to mark Rebwar’s post as the correct answer and get the question off the Unsolved list.

1 like

Please or to participate in this conversation.