我试图在 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();
});
现在我想要的是,"问题"表中名为"best_answer_id
"的列应该是约束到"答案"表中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 无法创建表
(laravel-qa
。questions
(errno: 150 "外键约束格式不正确"( (SQL: 更改表questions
添加约束questions_best_answer_id_foreign
外键 (best_answer_id
( 引用answers
(id
( 删除 SET NULL( (
作为旁注,我知道 references((->on(( 已针对 Laravel 7 进行了更改,它现在可以与 concured(( 一起使用,但两种情况下的错误保持不变。请帮我解决这个问题。
感谢和亲切的问候
->id()
->bigInteger()
不是->integer()
而且它也是未签名的。 由于列类型必须匹配才能具有外键约束,因此它应该是:
$table->unsignedBigInteger('best_answer_id')->nullable();
欧洲工商管理学院:
$table->integer('best_answer_id')->nullable();
在终端中,运行:
php artisan make:migration modify_best_answer_id_to_bigint_unsigned_not_null_to_questions_table
--table=questions
它为您创建了一个迁移文件,用于更改"best_answer_id"的数据类型。
在迁移文件的 up(( 方法中,使用 unsignedBigInterger('best_answer_id'(->nullable((->change(( 更改"best_answer_id";
public function up()
{
Schema::table('questions', function (Blueprint $table) {
$table->unsignedBigInteger('best_answer_id')->nullable()->change();
});
}
然后,在终端中运行:
php artisan make:migration add_foreign_best_answer_id_to_questions_table --table=questions
然后,在此迁移文件中,将外来"best_answer_id"添加到问题表中:
public function up()
{
Schema::table('questions', function (Blueprint $table) {
$table->foreign('best_answer_id')
->references('id')
->on('answers')
->onDelete('SET NULL');
});
}
最后,运行:
php artisan migrate
它对我有用。 希望它能为你工作!