【问题标题】:Laravel CRUD delete not working on foreign keyLaravel CRUD 删除不适用于外键
【发布时间】:2017-03-31 00:28:34
【问题描述】:

我与数据库中的 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)

请帮忙。

【问题讨论】:

    标签: php mysql laravel laravel-5.2


    【解决方案1】:

    我的赌注是外键设置为 ON DELETE RESTRICT 而不是 CASCADE。

    无法删除或更新父行:外键约束失败(fitilicious.products, CONSTRAINT products_category_id_foreign FOREIGN KEY (category_id) REFERENCES categories (id))(SQL:删除来自categories,其中id = 2)

    这告诉我们“产品”表中有一行引用了您尝试删除的类别。

    • ON DELETE CASCADE 也会删除产品。
    • ON DELETE RESTRICT 将阻止删除非空类别
    • ON DELETE SET NULL 将删除产品表中的类别并将 category_id 设置为 NULL

    各有各的用途,但你需要选择你需要的。

    【讨论】:

    • 但是我们在 laravel delete 中写什么代码来完成这个
    猜你喜欢
    • 2017-06-05
    • 2017-01-16
    • 2018-03-10
    • 2018-09-18
    • 1970-01-01
    • 2016-03-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多