hi i am trying to make category and then subcategory so if a category is deleted subcategory would also be deleted here what i have done so far created a model called category also created a subcategory model
run the migration for the category
public function up() { Schema::create('categories', function (Blueprint $table) { $table->increments('id'); $table->string('name'); $table->string('image'); $table->string('slug'); $table->timestamps(); }); }
in my subcategories migration i have defined the
public function up() { Schema::create('subcategories', function (Blueprint $table) { $table->increments('id'); $table->unsignedBigInteger('category_id'); $table->string('name'); $table->string('slug'); $table->timestamps(); $table->foreign('category_id')->references('id')->on('categories')->onDelete('cascade'); }); }
when i try to migrate i am running in to error which states that IlluminateDatabaseQueryException
SQLSTATE[HY000]: General error: 1215 Cannot add foreign key constraint (SQL: alter table subcategories
add constraint subcategories_category_id_foreign
foreign key (category_id
) references categories
(id
) on delete cascade)
my laravel version is 8.40 nd sqlversion is 5.7.24
did change the timestamp of both tables still it didn’t work
2021_06_09_000000_create_categories_table.php 2021_06_10_055026_create_subcategories_table.php
even i tried
$table->foreignId('category_id')->constrained('categories');
Advertisement
Answer
Schema::create('categories', function (Blueprint $table) { $table->increments('id'); $table->string('name'); $table->string('image'); $table->string('slug'); $table->timestamps(); });
Schema::create('subcategories', function (Blueprint $table) { $table->increments('id'); $table->unsignedInteger('category_id'); $table->string('name'); $table->string('slug'); $table->timestamps(); $table->foreign('category_id')->references('id')->on('categories')->onDelete('cascade'); });