Laravel, миграции. Ошибка errno: 150 «Foreign key constraint is incorrectly formed», как исправить?

Здравствуйте!

Пытаюсь создать три таблицы в базе, две из которых связанных по ключу id – с первой. В соответствии с документацией laravel создал фалы миграций:
Schema::create('pechniks', function (Blueprint $table) {
            $table->bigIncrements('id');
            $table->string('name');
            $table->string('photo', 100)->nullable();
            $table->boolean('active')->default(true);
            $table->string('city')->nullable();
            $table->string('info')->nullable();
            $table->string('phone')->nullable();
            $table->string('email')->nullable();
            $table->text('description')->nullable();
            $table->timestamps();
        });

        Schema::create('images', function (Blueprint $table) {
            $table->bigIncrements('id');
            $table->integer('pechnik_id')->unsigned();
            $table->foreign('pechnik_id')->references('id')->on('pechniks');
            $table->string('img');
            $table->timestamps();
        });

        Schema::create('diplomas', function (Blueprint $table) {
            $table->bigIncrements('id');
            $table->integer('pechnik_id')->unsigned();
            $table->foreign('pechnik_id')->references('id')->on('pechniks');
            $table->string('img');
            $table->timestamps();
        });

Однако, при запуске миграций возникает сообщение об ошибке.
SQLSTATE[HY000]: General error: 1005 Can't create table `test`.`images` (errno: 150 "Foreign key constraint is incorrectly formed") (SQL: alter table `images` add constraint `images_pechnik_id_foreign` foreign key (`pechnik_id`) references `pechniks` (`id`))


Полагаю, что что-то не то с внешними ключами – на это указывает сообщение об ошибке. Но в чем причина и как это исправить?
  • Вопрос задан
  • 1573 просмотра
Решения вопроса 1
Fragster
@Fragster
помогло? отметь решением!
Типы $table->bigIncrements('id'); и $table->integer('pechnik_id')->unsigned(); не совпадают
Ответ написан
Пригласить эксперта
Ответы на вопрос 1
@KamishiroIyamoto
Ответ для Laravel 9.16:
добавили возможность указывать id просто как id(). Это bigInteger unsigned. Соответственно внешний ключ нужно создавать bigInteger unsigned.
Schema::create('blog_posts', function (Blueprint $table) {
            $table->id();

            $table->bigInteger('category_id')->unsigned();
            $table->bigInteger('user_id')->unsigned();

            $table->foreign('user_id')->references('id')->on('users');
            $table->foreign('category_id')->references('id')->on('blog_categories');
        });
Ответ написан
Комментировать
Ваш ответ на вопрос

Войдите, чтобы написать ответ

Войти через центр авторизации
Похожие вопросы