MySQL Query获取类别和子级

时间:2017-01-15 09:41:10

标签: php mysql laravel

我很擅长与MySQL交流。我有一个我无法修改的数据库(现有系统),我必须得到可用的类别及其子项。

如果我使用laravel的查询构建器运行以下查询,我会得到所有类别和子项,如下所示:

DB::table('tblknowledgebasecats')->get();

// Returns

    Collection {#337 ▼
      #items: array:13 [▼
        0 => {#338 ▼
          +"id": 1
          +"parentid": 0
          +"name": "System"
          +"description": "..."
          +"hidden": ""
          +"catid": 0
          +"language": ""
        }
        1 => {#340 ▼
          +"id": 3
          +"parentid": 0
          +"name": "Help"
          +"description": "Some Description"
          +"hidden": ""
          +"catid": 0
          +"language": ""
        }
        2 => {#341 ▼
          +"id": 4
          +"parentid": 0
          +"name": "Troubleshooting"
          +"description": "..."
          +"hidden": ""
          +"catid": 0
          +"language": ""
        }
        3 => {#342 ▼
         +"id": 5
         +"parentid": 1
         +"name": "Installation"
         +"description": ""
         +"hidden": ""
         +"catid": 0
         +"language": ""
        }

正如您所看到的,ID为5的结果的parentid为1,我如何查询它以便它们被链接'一起?它用于构建菜单。输出必须是这样的,用于在视图中呈现菜单:

- System
    -- Istallation
    -- ...
- Help
    -- ....
-Troubleshooting
- ...

1 个答案:

答案 0 :(得分:1)

我有一个快速的解决方案,使用递归来查找子类别,但它在性能方面可能不是最好的,因为它会触发多个查询

laravel方法是创建Eloquent model而不是使用DB Facade。在您的模型类中,请说App \ Category添加以下内容:

public static function getChildren(App\Category $category) {
return static::where('parentid', $category->id)->get();
}

现在,在控制器功能中显示菜单,添加以下内容:

$parentcategories = App\Category::where('parentid', 0)->get();
return view('displaymenus', ['categories' => $parentcategories]);

在主视图中,添加以下内容:

<!-- View stored in resources/views/displaymenus.blade.php -->
<ul>
@foreach($categories as $category)
<li> {{ $category->name }} @include('displaysubmenus', compact('category')) </li>
@endforeach
</ul>

在子菜单视图中,添加以下内容:

<!-- View stored in resources/views/displaysubmenus.blade.php -->
<ul>
@foreach(App\Category::getChildren($category) as $subcategory)
<li> {{ $subcategory->name }} @include('displaysubmenus', ['category' => $subcategory]) </li>
@endforeach
</ul>