В пустом проекте Laravel я хочу создать ограничение внешнего ключа между пользователями и вопросами , где users
таблица будет содержать встроенный Laravel User
, но Question
будет пользовательской моделью.
После выполнения php artisan migrate
возникает ошибка follownign:
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|
Вот миграция create_users_table, сгенерированная 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();
});
И вот моя миграция:
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');
});
Я пытался разделить создание таблицы вопросов и изменение с ограничением внешнего ключа на две миграции, но получил ту же ошибку.Обратите внимание, что не связанные ответы на stackoverflow были полезны для меня.