lukasoppermann's avatar

Foreign key in mysql error: General error: 1215 Cannot add foreign key constraint

Hey,

I am using some polymorphic many to many relationships. I was using sqlite and it worked like a charm. However trying to switch to mysql now gives me trouble.

 [Illuminate\Database\QueryException]
SQLSTATE[HY000]: General error: 1215 Cannot add foreign key constraint (SQL: alter table `fragmentables` add constraint `fragmentables_fragment_id_foreign` foreign key (`fragment_id`) references `fragments` (`id`) on delete cascade)
public function up()
    {
        Schema::create('fragmentables', function (Blueprint $table) {

            $table->increments('id');

            $table->uuid('fragment_id')->index();
            $table->foreign('fragment_id')->references('id')->on('fragments')->onDelete('cascade');

            $table->uuid('fragmentable_id')->index();
            $table->string('fragmentable_type');

        });

    }
public function up()
    {
        Schema::create('fragments', function (Blueprint $table) {

            $table->uuid('id')->index();
            $table->string('name', 100)->nullable();
            $table->string('type')->nullable();
            $table->json('data')->nullable();
            $table->timestamps();
            $table->softDeletes();
        });
    }

Any idea why? What do I have to do to fix this?

0 likes
1 reply
lukasoppermann's avatar

Hey, so apparently something was screwed up. The solution is to make sure all ids are indexed.

$table->uuid('id')->index();

I changed to sqlite and back to mysql and now it works, somehow it is InnoDB by default.

Please or to participate in this conversation.