[英]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. 我与数据库中的category_id列有外部关系,但是在删除时出现错误。 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. 我的赌注是将外键设置为ON DELETE RESTRICT而不是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) 无法删除或更新父行,外键约束失败(fitilicious
。products
,约束products_category_id_foreign
外键(category_id
)参考文献categories
(id
))(SQL:从删除categories
,其中id
= 2)
This tells us that there is a row in table "products" which is referencing the category you are attempting to delete. 这告诉我们表“ products”中有一行,它引用您要删除的类别。
Each has its uses, but you need to choose which one you need. 每种都有其用途,但是您需要选择所需的一种。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.