@sagaton

Не удается связать две таблицы через foreign. Как исправить ошибку 1215?

Почему возникать ошибка
SQLSTATE[HY000]: General error: 1215 Cannot add foreign key constraint (Connection: mysql, SQL: alter table `products` add constraint `products_category_id_foreign` foreign key (`category_id`) references `categories` (`id`) on del
ete set null)


Имеется таблица категории:

Schema::create('categories', function (Blueprint $table) {
            $table->id();
            $table->string('name');
            $table->boolean('is_active')->default(1);
            $table->timestamps();

        });


И таблица Продукт:
Schema::create('products', function (Blueprint $table) {
            $table->id();
            $table->string('title');
            $table->text('description');
            $table->text('article');
            $table->text('price');
            $table->boolean('is_promotion')->default(0);
            $table->integer ('%_promotion');
            $table->unsignedInteger('category_id')->index();
            $table->boolean('is_active')->default(1);
            $table->unsignedBigInteger('brand_id')->nullable();
            $table->unsignedBigInteger('warranty_id')->nullable();
            $table->unsignedBigInteger('color_id')->nullable();
            $table->text('material')->nullable();//несколько значений
            $table->string('country');
            $table->integer ('weight');
            $table->timestamps();
            $table->foreign('category_id')->references('id')->on('categories')->nullOnDelete();
            $table->foreign('brand_id')->references('id')->on('brand')->nullOnDelete();
            $table->foreign('warranty_id')->references('id')->on('warranty')->nullOnDelete();
            $table->foreign('color_id')->references('id')->on('colo')->nullOnDelete();
        });

При попытке накатить миграцию, возникает ошибка.
  • Вопрос задан
  • 334 просмотра
Пригласить эксперта
Ответы на вопрос 1
Enokin
@Enokin
Full-stack разработчик
$table->unsignedInteger('category_id')->nullable()->index();

Сделай так. Он тебе пишет что не может сделать из-за того что в category_id нельзя постить null значения
Ответ написан
Комментировать
Ваш ответ на вопрос

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

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