外键约束格式不正确-Laravel 7

时间:2020-06-05 09:20:39

标签: php mysql laravel laravel-7

我试图使用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表的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 migration`时,它会抛出一个奇怪的错误,显示为

SQLSTATE [HY000]:常规错误:1005无法创建表laravel-qaquestions(错误号:150“外键约束格式不正确”)(SQL:更改表{{1} }在删除SET NULL时添加约束questions外键(questions_best_answer_id_foreign)引用best_answer_idanswers

作为旁注,我知道Laravel 7的references()-> on()已更改,现在它可以与constrained()一起使用,但两种情况下的错误都相同。请帮我解决这个问题。

感谢和亲切问候

2 个答案:

答案 0 :(得分:0)

->id()->bigInteger()而不是->integer() 并且它也是未签名的。 由于列类型必须匹配才能具有外键约束,所以它应该是:

$table->unsignedBigInteger('best_answer_id')->nullable();

的目的:

        $table->integer('best_answer_id')->nullable();

答案 1 :(得分:0)

在您的终端中,运行:

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

它对我有用。 希望对你有用!

相关问题