seanmccabe's avatar

Test failing due to Foreign Key Constraint

Trying to run testing, and all of them are failing (default included Laravel) due to the error General error: 3734 Failed to add the foreign key constraint.

If I remove this line from the migration, it gets to the next migration that has a foreign key and it fails for the same reason.

Example migration:

Schema::create('user_profiles', function (Blueprint $table) {
   $table->unsignedBigInteger('user_id', false);
   $table->string('first_name', 50);
   $table->string('last_name', 50);
   $table->date('d_o_b')->nullable();
   $table->timestamps();

   $table->foreign('user_id')->references('user_id')->on('users')->onDelete('cascade')->onUpdate('cascade');
});

.env.ci

DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=test
DB_USERNAME=root

PHP Unit

<env name="APP_ENV" value="testing"/>
<env name="BCRYPT_ROUNDS" value="4"/>
 <env name="CACHE_DRIVER" value="array"/>
<!-- <env name="DB_CONNECTION" value="testing"/> -->
<!-- <env name="DB_DATABASE" value=":memory:"/> -->
<env name="MAIL_MAILER" value="array"/>
<env name="QUEUE_CONNECTION" value="sync"/>
<env name="SESSION_DRIVER" value="array"/>
<env name="TELESCOPE_ENABLED" value="false"/>

This is driving my nuts, so really would appreciate some help in solving this one.

0 likes
3 replies
sanusi's avatar
$table->foreign('user_id')->references('id')->on('users')->onDelete('cascade')->onUpdate('cascade');

or you can simply add the foreign key this way while creating the column

 $table->unsignedBigInteger('user_id')->foreign()->references('id')->on('users')->onDelete('cascade')->onUpdate('cascade');
1 like
seanmccabe's avatar

@sanusi Thanks, clearly been at this too long today, could not see that at all.

1 like
tykus's avatar

Is users.user_id the primary key?

Is users.user_id the same type (unsignedBigInteger) as the foreign key on user_profiles.user_id?

The Conditions and Restrictions section of the docs might throw some light on potential causes also?

Please or to participate in this conversation.