简体   繁体   中英

Laravel CRUD delete not working on foreign key

I have a foreign relationship with category_id column in database but while deleting i get error. This is my code for delete:

  public function destroy($id)
{
    $category = Category::find($id);
    $category->delete();
    Session::flash('success', 'The category was successfully deleted.');
    return redirect()->route('categories.index');
}

Error i seen is :

SQLSTATE[23000]: Integrity constraint violation: 1451 Cannot delete or update a parent row: a foreign key constraint fails (`fitilicious`.`products`, CONSTRAINT `products_category_id_foreign` FOREIGN KEY (`category_id`) REFERENCES `categories` (`id`)) (SQL: delete from `categories` where `id` = 2)

Please help.

My bet is on the foreign key being set to ON DELETE RESTRICT instead of CASCADE.

Cannot delete or update a parent row: a foreign key constraint fails ( fitilicious . products , CONSTRAINT products_category_id_foreign FOREIGN KEY ( category_id ) REFERENCES categories ( id )) (SQL: delete from categories where id = 2)

This tells us that there is a row in table "products" which is referencing the category you are attempting to delete.

  • ON DELETE CASCADE will also delete the product.
  • ON DELETE RESTRICT will prevent deletion of a non-empty category
  • ON DELETE SET NULL will delete the category and set category_id to NULL in products table

Each has its uses, but you need to choose which one you need.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM