Home > Back-end >  I have tables: categories & items table which has a foreign key of $category_id. How can I delete a
I have tables: categories & items table which has a foreign key of $category_id. How can I delete a

Time:11-09

I can't delete a category because it is a foreign key in the items table. How can I do it? How can I make a deletion in category and make $category_id null in the items table?

I tried making a delete function but it sends an error saying it can't because it is a foreign key.

CodePudding user response:

Create a migration to allow the field category_id to have null value and to default to null when the referenced category is deleted by setting onDelete null on foreign key

$table->foreignId('category_id')->nullable()->constrained()->onDelete('set null');

You can also read from here

Official Docs

CodePudding user response:

DB::statement('SET FOREIGN_KEY_CHECKS=0;');
// write your delete code here
DB::statement('SET FOREIGN_KEY_CHECKS=1;');
  • Related