在一个空白的 Laravel 项目中,我想在之间创建外键约束users and 问题, where users
表将容纳内置 LaravelUser
, but Question
将是一个定制模型。
运行后php artisan migrate
出现以下错误:
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|
这是 laravel 生成的 create_users_table 迁移:
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 上的相关答案对我没有帮助。