无限极分类

 

class CategoryController extends Controller
{
    public function index()
    {
        $rootCats = Category::where('parent_id', null)->get();
        return $this->tree($rootCats);
    }

    private function tree($cats) {
        $tree = [];
        foreach ($cats as $cat) {
            $childrenCats = Category::where('parent_id', $cat->id)->get();
            if ($childrenCats->isNotEmpty()) {
                $cat->children = $this->tree($childrenCats);
            }
            $tree[] = $cat;
        }
        return $tree;
    }
}

 

你可能感兴趣的:(无限极分类)