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
, CONSTRAINTproducts_category_id_foreign
FOREIGN KEY (category_id
) REFERENCEScategories
(id
)) (SQL: delete fromcategories
whereid
= 2)
This tells us that there is a row in table "products" which is referencing the category you are attempting to delete.
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.