【发布时间】:2020-09-24 11:09:46
【问题描述】:
我试图在 Laravel 7 中使用新的迁移将列设置为 foreignID,但我遇到了一个奇怪的错误。
我会一步一步来,这样大家就清楚了。
首先,我使用下面的迁移创建了一个问题表 -
Schema::create('questions', function (Blueprint $table) {
$table->id();
$table->string('title');
$table->string('slug')->unique();
$table->longText('body');
$table->unsignedInteger('views')->default(0);
$table->unsignedInteger('answers_count')->default(0);
$table->integer('votes')->default(0);
$table->integer('best_answer_id')->nullable();
$table->foreignId('user_id')->constrained()->onDelete('cascade');
$table->timestamps();
});
在上表中,user_id 是一个外键,包含在 users 表中的用户 ID 中。这工作得很好。
然后我使用以下迁移创建了一个Answers 表
Schema::create('answers', function (Blueprint $table) {
$table->id();
$table->integer('question_id');
$table->foreignId('user_id')->constrained()->onDelete('cascade');
$table->longText('body');
$table->integer('votes_count')->default(0);
$table->timestamps();
});
现在我想要的是,在 Questions 表中名为 best_answer_id 的列应该是限制在 Answers 表中的 id 的外键。
为了实现这一点,我创建了一个名为 make_foreign_best_answers_id_in_questions 的新迁移,迁移在这里:
Schema::table('questions', function (Blueprint $table) {
$table->foreign('best_answer_id')
->references('id')
->on('answers')
->onDelete('SET NULL');
});
据我所知,这应该将 best_answer_id 列设置为应该引用答案表中的 ID 的外部 ID。
在运行 `php artisan migrate`` 时会抛出一个奇怪的错误,内容如下:
SQLSTATE[HY000]: 一般错误: 1005 Can't create table
laravel-qa.questions(errno: 150 "外键约束格式不正确") (SQL: alter tablequestionsadd constraintquestions_best_answer_id_foreign删除 SET NULL 时外键 (best_answer_id) 引用answers(id)
附带说明,我知道 Laravel 7 中的 references()->on() 已更改,现在它可以与 constrained() 一起使用,但两种情况下的错误仍然相同。请帮我解决这个问题。
感谢和亲切的问候
【问题讨论】:
标签: php mysql laravel laravel-7