Laravel не может добавить внешний ключ, даже если он назначен как неподписанный - PullRequest
0 голосов
/ 10 февраля 2020

У меня есть таблица с именем 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")")

Ответы [ 2 ]

1 голос
/ 10 февраля 2020

Теперь, когда вы сопоставили типы, причина его сбоя в том, что другой ключ не проиндексирован, внешний ключ создает индекс в таблице, но ему также нужен один в другой таблице.

Поместите следующее в ваш выбор миграции:

$table->bigInteger('choice_id')->unsigned()->index(); 
0 голосов
/ 10 февраля 2020

Вы пытались изменить тип choice_id в таблице choices на большие приращения.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...