简体   繁体   English

Laravel CRUD删除不适用于外键

[英]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 , CONSTRAINT products_category_id_foreign FOREIGN KEY ( category_id ) REFERENCES categories ( id )) (SQL: delete from categories where id = 2) 无法删除或更新父行,外键约束失败( fitiliciousproducts ,约束products_category_id_foreign外键( category_id )参考文献categoriesid ))(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”中有一行,它引用您要删除的类别。

  • ON DELETE CASCADE will also delete the product. ON DELETE CASCADE也将删除该产品。
  • ON DELETE RESTRICT will prevent deletion of a non-empty category ON DELETE RESTRICT将防止删除非空类别
  • ON DELETE SET NULL will delete the category and set category_id to NULL in products table ON DELETE SET NULL将删除类别并将产品表中的category_id设置为NULL

Each has its uses, but you need to choose which one you need. 每种都有其用途,但是您需要选择所需的一种。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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