我与数据库中的category_id 列有外部关系,但在删除时出现错误。 这是我的删除代码:
public function destroy($id)
{
$category = Category::find($id);
$category->delete();
Session::flash('success', 'The category was successfully deleted.');
return redirect()->route('categories.index');
}
我看到的错误是:
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)
请帮忙。
最佳答案
我的赌注是将外键设置为 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)
这告诉我们表“products”中有一行引用了您尝试删除的类别。
- ON DELETE CASCADE 也会删除该产品。
- ON DELETE RESTRICT 将阻止删除非空类别
- ON DELETE SET NULL 将删除产品表中的类别并将category_id 设置为 NULL
每种都有其用途,但您需要选择您需要的。
关于php - Laravel CRUD 删除不适用于外键,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43123453/