Reputation:
I want to use two models on my laravel 7.x application : Users and Images :
# Users migration : 2014_10_12_000000_create_users_table.php
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();
});
# Images migration : 2020_03_27_121254_create_models_images_table
Schema::create('images', function (Blueprint $table) {
$table->bigIncrements('id');
$table->bigInteger('user_id')->unsigned;
$table->string('name');
$table->timestamps();
});
Schema::table('images', function (Blueprint $table) {
$table->foreign('user_id')->references('id')->on('users')->onDelete('cascade');
});
When trying to migrate i receive following error : General error: 1215 Cannot add foreign key constraint (SQL: alter table images
add constraint images_user_id_foreign
foreign key (user_id
) references users
(id
) on delete cascade)
I have already searched over google without success, someone could helps me please ?
Thank you
Upvotes: 0
Views: 2559
Reputation: 14941
You are not setting the unsigned
properly.
Replace:
$table->bigInteger('user_id')->unsigned;
By:
$table->bigInteger('user_id')->unsigned();
Since the user_id
is not unsigned, the definition does not match the id
of the users
table which means you cannot set the foreign key.
You could also do:
$table->unsignedBigInteger('user_id');
As of Laravel 7, you can do it like this in your users
migration:
Schema::table('users', function (Blueprint $table) {
$table->id();
// ...
});
And in your images
migration:
Schema::table('users', function (Blueprint $table) {
// ...
$table->foreignId('user_id')->constrained();
});
You can find more information here: https://laravel.com/docs/7.x/migrations#foreign-key-constraints
Upvotes: 1
Reputation: 5682
You are missing bracket in unsiged()
As per Laravel Documentation
->unsigned()
SetINTEGER
columns asUNSIGNED
(MySQL)
Change
$table->bigInteger('user_id')->unsigned;
to
$table->bigInteger('user_id')->unsigned();
Upvotes: 0