用于删除Laravel中嵌套类别的递归函数

时间:2017-07-14 03:20:45

标签: php laravel laravel-5 eloquent

我有这张桌子

id - parent_id - name 
1 - 0 - T-shirts 
2 - 1 - Red T-shirts 
3 - 1 - Black T-shirts 
4 - 0 - Sweaters 
5 - 4 - Red Sweaters 
6 - 4 - Blue

可以有六个嵌套类别

递归函数,当我选择删除id

时,按父ID删除所有嵌套类别

例如,当我删除T恤时,应该删除红色T恤和黑色T恤,并且嵌套类别 穆罕默德·艾琳 我写这些功能,但有阻止页面 穆罕默德·艾琳 获取我想删除的所有id并存储在一个数组中以便一次性销毁所有togather

瞧瞧功能

protected $theArray = array();

public function recursiveDelete($v)
{
  $toRecurses = Car::where('parent_id', $v )->get();
  foreach( $toRecurses as $toRecurse ){
    array_push( $this->theArray, $toRecurse->id );
  }
  foreach( $toRecurses as $toRecurse ){
    if( Car::where('parent_id' , $toRecurse->id)->get()->first() ){
      return $this->recursiveDelete( $toRecurse );
      //dd( Car::where('parent_id' , $toRecurse->id)->get()->first() );
    }
  }
}

public function testForDeletingCar(Car $carD, $id)
{
  $c = $carD::where('id' , $id)->get()->first();
  $this->recursiveDelete( $c->id );
  return $this->theArray;
}

1 个答案:

答案 0 :(得分:1)

假设模型名称为Category ..在模型类中添加以下方法[category.php file]:

public function children(){
    return $this->hasMany('App\Category', 'parent_id', 'id');
}

在控制器类CategoryController.php中,使用以下代码

public function destroy($id){
    // Getting the parent category
    $parent = \App\Category::findOrFail($id);
    // Getting all children ids
    $array_of_ids = $this->getChildren($parent);
    // Appending the parent category id
    array_push($array_of_ids, $id);
    // Destroying all of them
    \App\Category::destroy($array_of_ids);
}

private function getChildren($category){
    $ids = [];
    foreach ($category->children as $cat) {
        $ids[] = $cat->id;
        $ids = array_merge($ids, $this->getChildren($cat));
    }
    return $ids;
}