【问题标题】:Laravel can't add foreign key even if assigned as unsigned即使分配为无符号,Laravel 也无法添加外键
【发布时间】:2020-05-25 21:01:45
【问题描述】:

我有一个名为choices 的表,我希望choice_id 是主键,但不是自动递增,因为我有一个播种机。

这是我对choices 的迁移

     Schema::create('choices', function (Blueprint $table) {
            $table->bigInteger('choice_id')->unsigned();
            $table->bigInteger('question_id')->unsigned();
            $table->string('choice');
            $table->integer('value');
            $table->timestamps();
        });

        Schema::table('choices',function (Blueprint $table){
            $table->foreign('question_id')
                    ->references('question_id')
                    ->on('questions');
        });

还有,这里是答案

     Schema::create('answers', function (Blueprint $table) {
            $table->bigInteger('user_id')->unsigned();
            $table->bigInteger('question_id')->unsigned();
            $table->bigInteger('choice_id')->unsigned();
            $table->timestamps();
        });

        Schema::table('answers',function (Blueprint $table){
            $table->foreign('question_id')
                    ->references('question_id')
                    ->on('questions');

            $table->foreign('choice_id')
                    ->references('choice_id')
                    ->on('choices');

            $table->foreign('user_id')
                    ->references('user_id')
                    ->on('schedules');
        });

当我迁移时,我得到了

SQLSTATE[HY000]: General error: 
1005 Can't create table
`scheduler`.`answers` (errno: 150 "Foreign key constraint is incorrectly formed") 
(SQL: alter table `answers` add constraint
`answers_choice_id_foreign` foreign key (`choice_id`) references `choices` (`choice_id`))

PDOException::("SQLSTATE[HY000]: 
General error: 1005 Can't create table `scheduler`.`answers` (errno: 150 "Foreign key constraint is incorrectly formed")")

【问题讨论】:

  • 您没有将unsigned 添加到choices 中的choice_id,因此它可能与答案中的choice_id 不匹配。
  • 即使我将$table->bigInteger('choice_id')->unsigned(); 放入choices 我得到了同样的错误先生@aynber
  • 现在choices 中的choice_idbigInteger,但answers 中的choice_id 只是integer。那些应该匹配。 (而不是先生)
  • 相同,我将其更改为$table->bigInteger('choice_id')->unsigned(); 仍然得到相同的错误。我不知道为什么会这样

标签: php mysql sql laravel migration


【解决方案1】:

您是否尝试过将choices 表中choice_id 的类型更改为较大的增量。

【讨论】:

    【解决方案2】:

    既然您已经匹配了类型,它失败的原因是另一个键没有被索引,一个外键在表中创建了一个索引,但它也需要另一个表中的一个。

    在您的选择迁移中添加以下内容:

    $table->bigInteger('choice_id')->unsigned()->index(); 
    

    【讨论】:

      猜你喜欢
      • 2021-12-14
      • 2020-09-12
      • 2016-02-11
      • 2019-10-26
      • 1970-01-01
      • 1970-01-01
      • 2022-01-26
      • 2021-10-27
      • 2018-11-25
      相关资源
      最近更新 更多