如果有产品,如何删除类别?

时间:2016-01-26 03:43:21

标签: laravel-4

我的产品有一个类别名称:“短裤”。因此,如果我删除类别名称短裤,产品也将被删除。所以,我想,如果短片将被删除,它将不会删除,因为它有一个产品。请帮帮我

我删除类别的功能......

   public function destroy(){
         $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')
            ->with('message', 'Something went wrong');

1 个答案:

答案 0 :(得分:0)

首先,您需要检查某个产品是否属于该类别

Product::where('category_id', Input::get('id'))->count();

如果计数不大于0,则只删除该类别。*未测试*

$products = Product::where('category_id', Input::get('id'))->count();
    if($products > 0){
         return Redirect::to('admin/categories')
                ->with('message', 'Something went wrong');
    }
    else{
        $category= Category::find(Input::get('id'));
        $category->delete();
        return Redirect::to('admin/categories/index')
                    ->with('message', 'Category Deleted');
    }