I have an orders table and a have a sell_shipping_labels
which references orders.id
as a foreign. However when I run the Laravel migration I get th
Primary key and foreign key should be in the same data type.
If the primary key is using unsigned big_integer
, the foreign key should also be using unsigned big_integer
.
In case laravel 5.8 uses bigIncrements
by default when generating new migration (see this pull request), you should make sure that your foreign key
is also big_increment
or you will get error.
Table users
:
Schema::create('users', function (Blueprint $table) {
$table->bigIncrements('id');
$table->string('name');
...
}
Table orders
:
Schema::create('orders', function (Blueprint $table) {
$table->bigIncrements('id');
$table->unsignedBigInteger('user_id');
...
$table->foreign('user_id')->references('id')->on('users');
}
Hope this helps.
For those which marked answer didn't work:
Check your tables engine. In my case, I was referencing on a MyISAM table in an InnoDB source table. After changing the reference table engine to InnoDB, it worked!
Better way to add foreign key in Laravel is using the alias. So instead of:
$table->unsignedBigInteger('user_id'); // foreigh key
$table->foreign('user_id')->references('id')->on('users')->onDelete('cascade');
We can simply do this:
$table->foreignId('user_id')->constrained();
And that works for me. Thanks!
Most times the reason for this error is usually due to the order of which the migration files are listed or error due to type casting.
Always make sure that the migration of the file which the foreign constraints is to be imposed on comes after the parent migration. And for the latter, make sure its an unsignedBigInteger , although former version of laravel (<5.4) could ignore this type casting error.
[![enter image description here][1]][1]
public function up()
{
Schema::create('users', function (Blueprint $table) {
$table->bigIncrements('id');
$table->string('name');
$table->string('email')->unique();
$table->timestamp('email_verified_at')->nullable();
$table->string('password');
$table->rememberToken();
$table->timestamps();
});
}
I changed $table->bigIncrements('id') to $table->Increments('id')
For this user_id of files table become same integer type as user table field id. After this command worked.
public function up()
{
Schema::create('users', function (Blueprint $table) {
$table->increments('id');
$table->string('name');
$table->string('email')->unique();
$table->timestamp('email_verified_at')->nullable();
$table->string('password');
$table->rememberToken();
$table->timestamps();
});
}
For the second table
{
Schema::create('files', function (Blueprint $table) {
$table->increments('id');
});
Schema::table('files', function($table) {
$table->foreign('user_id')->references('id')->on('users')->onDelete('cascade');
});
}