In a blank Laravel project, I want to create foreign key constraint between users and questions, where users table will hold build-in Laravel User, but Question will be a custom model.
After running php artisan migrate the follownign error occurs:
Illuminate\Database\QueryException : SQLSTATE[HY000]: General error: 1215 Cannot add foreign key constraint (SQL: alter table `questions` add constraint `questions_user_id_foreign` foreign key (`user_id`) references `users` (`id`) on delete cascade)
at /home/artur/Exposit/EDU/PHP/lara/vendor/laravel/framework/src/Illuminate/Database/Connection.php:664
660| // If an exception occurs when attempting to run a query, we'll format the error
661| // message to include the bindings with SQL, which will make this exception a
662| // lot more helpful to the developer instead of just the database's errors.
663| catch (Exception $e) {
> 664| throw new QueryException(
665| $query, $this->prepareBindings($bindings), $e
666| );
667| }
668|
Here is create_users_table migration generated by laravel:
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();
});
And here is my migration:
Schema::create('questions', function (Blueprint $table) {
$table->bigIncrements('id');
$table->string('title');
$table->string('slug')->unique();
$table->text('body');
$table->unsignedInteger('views')->default(0);
$table->unsignedInteger('answers')->default(0);
$table->integer('votes')->default(0);
$table->unsignedInteger('best_answer_id')->nullable();
$table->unsignedInteger('user_id');
$table->timestamps();
});
Schema::table('questions', function (Blueprint $table) {
$table->foreign('user_id')->references('id')->on('users')->onDelete('cascade');
});
I've tried to separate questions table creation and altering with foreign key constraint into two migrations, but got the same error. Note, that non of related answers on stackoverflow were helpful to me.