errno: 150 "Ограничение внешнего ключа неправильно сформировано в миграции laravel 6 - PullRequest
0 голосов
/ 07 марта 2020

Я новичок в laravel и извините, если мой Engli sh плохой. Я сделал файл миграции и запустил его

  1. create_colleges_table. php

publi c function up () {

 Schema::create('colleges', function (Blueprint $table) {
        $table->bigIncrements('id');
        $table->string('name');
        $table->char('nim', 10);
        $table->string('email');
        $table->integer('major_id');
        $table->timestamps();
    });
}
create_majors_table. php

publi c function up () {

Schema::create('majors', function (Blueprint $table) {
        $table->bigIncrements('id');
        $table->string('major_name');
        $table->timestamps();
    });
}

А затем я делаю update_colleges_table. php, запускаю его и получаю ошибку вот так:

Illuminate\Database\QueryException  : SQLSTATE[HY000]: General error: 1005 Can't create table `learn_laravel_crud`.`#sql-1558_e3` (errno:
150 "Foreign key constraint is incorrectly formed") (SQL: alter table `colleges` add constraint `colleges_major_id_foreign` foreign key (`major_id`) references `majors` (`id`))

это мой код в update_colleges_table. php

publi c function up ()

{
    Schema::table('colleges', function (Blueprint $table){
        $table->foreign('major_id')->references('id')->on('majors');
    });

}

1 Ответ

1 голос
/ 07 марта 2020

Для создания Foreign key тип данных для child column должен точно соответствовать parent column.

Поскольку majors.id является bigIncrements, т.е. unsigned big integer, тогда colleges.major_id также должно быть bigInteger, а не integer.

Так что измените

 $table->integer('major_id');

на

$table->unsignedBigInteger('major_id');
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...