无法删除包含子级现有Laravel CRUD的父级

时间:2014-06-11 05:01:30

标签: sql laravel crud

当我尝试使用该父类别下的产品删除我的类别条目时,这是我抛出的错误:

Illuminate \ Database \ QueryException
SQLSTATE[23000]: Integrity constraint violation: 1451 Cannot delete or update a parent     row: a foreign key constraint fails (`store`.`products`, CONSTRAINT     `products_category_id_foreign` FOREIGN KEY (`category_id`) REFERENCES `categories` (`id`))    (SQL: delete from `categories` where `id` = 1)

在我做了一些研究后,我知道你不能删除有现有孩子的父母

删除类别ID时,我不确定如何使用我的类别ID加入产品。这样我就可以删除所有带有相关类别ID的产品。

以下是我的删除功能:

public function postDestroy() {
    $category = Category::find(Input::get('id'));

    if ($category) {
        $category->delete();
        return Redirect::to('admin/categories/index')
            ->with('message', 'Category Deleted');
    }

    return Redirect::to('admin/categories/index')
        ->with('message', 'Something went wrong, please try again');

} 

1 个答案:

答案 0 :(得分:3)

如果您要删除任何具有相同类别的产品,我会将您的类别类更改为具有以下类似内容:

class Category extends Eloquent
{
    // ... all your existing code...
    public function delete()
    {
        // Delete all of the products that have the same ids...
        Products::where("category_id", $this->id)->delete();

        // Finally, delete this category...
        return parent::delete();
    }
}

现在调用$ category-> delete()将删除所有具有相同category_id的产品以及类别本身。