0

Не пойму почему не могу сделать миграцию в бд вместе с внешними ключами. Вроде делаю всё правильно и выдаёт ошибку

    SQLSTATE[HY000]: General error: 1215 Cannot add foreign key constraint (SQL: alter table `cases` add constraint `cases_categories_id_foreign` foreign key (`categories_id`) references `categories` (`id`))

  at /Applications/MAMP/htdocs/laravel/MeowDrop/vendor/laravel/framework/src/Illuminate/Database/Connection.php:664
    660|         // If an exception occurs when attempting to run a query, we'll format the error
    661|         // message to include the bindings with SQL, which will make this exception a
    662|         // lot more helpful to the developer instead of just the database's errors.
    663|         catch (Exception $e) {
  > 664|             throw new QueryException(
    665|                 $query, $this->prepareBindings($bindings), $e
    666|             );
    667|         }
    668| 

  Exception trace:

  1   PDOException::("SQLSTATE[HY000]: General error: 1215 Cannot add foreign key constraint")
      /Applications/MAMP/htdocs/laravel/MeowDrop/vendor/laravel/framework/src/Illuminate/Database/Connection.php:458

  2   PDOStatement::execute()
      /Applications/MAMP/htdocs/laravel/MeowDrop/vendor/laravel/framework/src/Illuminate/Database/Connection.php:458

Вот миграция cases

Schema::create('cases', function (Blueprint $table) {
            $table->bigIncrements('id')->unique();

             $table->integer('categories_id')->unsigned();
             $table->integer('items_id')->unsigned();

            $table->string('name');
            $table->string('img');
            $table->integer('price');

            $table->string('slug');
            $table->timestamp('updated_at')->useCurrent();
            $table->timestamp('created_at')->useCurrent();
            $table->timestamp('deleted_at')->useCurrent();


            $table->foreign('categories_id')->references('id')->on('categories')->unsigned();
            $table->foreign('items_id')->references('id')->on('items');
        });

Миграция categories

Schema::create('categories', function (Blueprint $table) {
            $table->increments('id');
            $table->string('name');
        });

Миграция items

   Schema::create('items', function (Blueprint $table) {
        $table->increments('id');
        $table->integer('assets_id');
        $table->string('name');
        $table->string('img');
        $table->integer('price');
    });
5
  • То же самое : SQLSTATE[HY000]: General error: 1215 Cannot add foreign key constraint (SQL: alter table cases add constraint cases_categories_id_foreign foreign key (categories_id) references categories (id)) Исправил порядок создания таблиц. теперь 2 строки таковы $table->foreign('categories_id')->references('id')->on('categories'); $table->foreign('items_id')->references('id')->on('items'); 28 апр 2019 в 11:59
  • Нужно именно друг за другом ?? 28 апр 2019 в 12:06
  • У меня в таком порядке. Categories - items - cases . Всё равно бьёт ошибку 28 апр 2019 в 12:10
  • Ой, ошибся оказалась 5.8.11. Извиняюсь 28 апр 2019 в 12:16
  • Изменил. Точно такая же ошибка ( 28 апр 2019 в 12:29

2 ответа 2

2

Расположите файлы по списку в следующем порядке:

  1. 2019_04_01_000011_create_items_table.php
  2. 2019_04_01_000022_create_categories_table.php
  3. 2019_04_01_000033_create_cases_table.php

Измените содержимое файлов миграций. Наличие метода down обязательно. Обратите внимание на поля типа bigIncrements и unsignedBigInteger:

public function up()
{
    Schema::create('items', function (Blueprint $table) {
        $table->bigIncrements('id');
        $table->integer('assets_id');
        $table->string('name');
        $table->string('img');
        $table->integer('price');
    });
}

public function down()
{
    Schema::drop('items');
}
public function up()
{
    Schema::create('categories', function (Blueprint $table) {
        $table->bigIncrements('id');
        $table->string('name');
    });
}

public function down()
{
    Schema::drop('categories');
}
public function up()
{
    Schema::create('cases', function (Blueprint $table) {
        $table->bigIncrements('id');

         $table->unsignedBigInteger('categories_id');
         $table->unsignedBigInteger('items_id');

        $table->string('name');
        $table->string('img');
        $table->integer('price');
        $table->string('slug');

        $table->timestamp('updated_at')->useCurrent();
        $table->timestamp('created_at')->useCurrent();
        $table->timestamp('deleted_at')->useCurrent();

        $table->foreign('items_id')->references('id')->on('items');
        $table->foreign('categories_id')->references('id')->on('categories');
    });
}

public function down()
{
    Schema::drop('cases');
}

Выполните в командной строке php artisan migrate:fresh.

Эта команда удалит все таблицы из Базы Данных и выполнит команду migrate

0
2

Во первых -

 $table->foreign('categories_id')->references('id')->on('categories')->unsigned();

unsigned здесь не нужен.

Во вторых - первая причина по которой это может не работать - у вас еще не создана таблица categories. Миграции выполняются в порядке создания.

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

2
  • Ничего не изменилось( 28 апр 2019 в 12:01
  • Добавьте имена файлов миграции в вопрос. Или можете сделать так - уберите создание внешних ключей из миграции, создайте таблицы, а потом добавьте ключи отдельной миграцией. Изменил ответ. 28 апр 2019 в 15:39

Ваш ответ

Нажимая на кнопку «Отправить ответ», вы соглашаетесь с нашими условиями использования и подтверждаете, что прочитали и поняли наши политику конфиденциальности и нормы поведения.

Всё ещё ищете ответ? Посмотрите другие вопросы с метками или задайте свой вопрос.