递归函数以删除Laravel中的嵌套类别 [英] Recursive function to delete nested categories in Laravel
问题描述
我有这张桌子
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删除所有嵌套类别
recursive function that delete all nested categorie by parent id when i choose to delete an id
示例,当我删除T恤时,应同时删除红色T恤和黑色T恤,并且嵌套类别穆罕默德·阿明(Mohamed Amine)我写那些功能,但有阻塞页面穆罕默德·阿明(Mohamed Amine)采取我要删除的所有ID并将其存储在数组中,以一次销毁所有的
example when i delete tshirt , both red t-shirt and black-tshirt should be deleted to and there nested categorie Mohamed Amine i write those function but there blocking page Mohamed Amine to take all the ids i want to delete and store in an array to destroy all togather in once
voila函数
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;
}
推荐答案
假设模型名称为 Category
..在模型类中添加以下方法[ category.php 代码>文件]:
Suppose that the Model name is Category
.. within the model class add the following method [category.php
file]:
public function children(){
return $this->hasMany('App\Category', 'parent_id', 'id');
}
在控制器类 CategoryController.php
中,使用以下代码
Within the controller class CategoryController.php
use the following code
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;
}
这篇关于递归函数以删除Laravel中的嵌套类别的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!