Support the ongoing development of Laravel.io →
posted 6 years ago

hello,

I have a table defined so:

$table->unsignedInteger('id');
            $table->integer('shipment_id')->nullable();
            $table->integer('customer_id');
            $table->integer('address_id');
            $table->string('appointed')->nullable();
            $table->string('causal')->nullable();
            $table->string('quantity')->nullable();
            $table->string('weight')->nullable();
            $table->string('appearance')->nullable();
            $table->string('carriage')->nullable();
            $table->date('transport_time')->nullable();
            $table->unsignedInteger('year')->default(date('Y'));

            $table->primary(array('id', 'year'));

            $table->timestamps();

now I need to have another table, with foreign key:

$table->unsignedInteger('id');
            $table->unsignedInteger('ddt_id');
            $table->unsignedInteger('year')->default(date('Y'));
            $table->string('code')->nullable();
            $table->text('description');
            $table->string('quantity')->nullable();

            $table->primary(array('id', 'ddt_id', 'year'));
            $table->foreign('ddt_id')->references('id')->on('ddts')->onDelete('cascade');
            $table->foreign('year')->references('year')->on('ddts')->onDelete('cascade');

            $table->timestamps();

but obviously when I migrate I get:

General error: 1215 Cannot add foreign key constraint (SQL: alter table ddtrows add constraint ddtrows_year_foreign foreign key (year) references ddts (year) on delete cascade)

how do I set foreign key in this case?

thanks a lot

Last updated 3 years ago.
0

Sign in to participate in this thread!

Eventy

Your banner here too?

andrea giorg Joined 13 Sep 2018

Moderators

We'd like to thank these amazing companies for supporting us

Your logo here?

Laravel.io

The Laravel portal for problem solving, knowledge sharing and community building.

© 2025 Laravel.io - All rights reserved.