php 在Laravel中删除嵌套类别的递归函数

xghobddn  于 2022-12-28  发布在  PHP
关注(0)|答案(2)|浏览(141)

我有这张table

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恤都应该删除,并且我编写了嵌套类别Mohamed Amine函数,但阻塞页面Mohamed Amine获取我想要删除的所有ID,并存储在数组中,以一次性销毁所有集合
瞧功能

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;
}
mf98qq94

mf98qq941#

假设Model名称为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;
}
but5z9lq

but5z9lq2#

public function destroy(Category $category)
{
    $rel=Category::query();
    // The bottom condition checked until -
    // no more same number in the "parent" column with the "id" column

    if ($e=$rel->where('parent', $category->id)->count()){
       
        alert()->error('First, the sub Categories must be deleted');
        return back();
    }else {

        $category->delete();
        alert()->success('Deleted successfully);
        return back();
    }

}

相关问题