简体   繁体   English

在Laravel 5.2中创建嵌套的类别列表的面包屑

[英]Create a breadcrumb of nested lists of categories in Laravel 5.2

Table

+---------+-----------+-----------+
|      id |   name    | parent_id |
+---------+-----------+-----------+
|       1 | Supports  |        0  |    
|       2 | Mobile    |        0  |      
|       3 | Outdoor   |        1  |       
|       4 | Samsung   |        2  |   
|       5 | Cricket   |        3  |  
|       6 | Team A    |        5  |      
+---------+-----------+-----------+

Categories Model 分类模型

class Categories extends Model {

    public $table = "categories";
    protected $fillable = ['name', 'parent_id', 'status'];

    public function parentCat() {
        return $this->belongsTo(Categories::class, 'parent_id');
    }

    public function childrenCat() {
        return $this->hasMany(Categories::class, 'parent_id');
    }

} 

Controller Method 控制器方式

Categories::where('parent_id', $parent_id)->orderBy('name', 'ASC')->get();

Question one 问题一

I want to show a breadcrumb with category and subcategory, if i am viewing cricket subcategories such as: 如果要查看板球子类别,我想显示带有类别和子类别的面包屑:

Home -> Supports -> Outdoor -> Cricket 主页->支持->户外->板球

Question two 问题二

How to delete all subcategory while deleting main categoriy. 如何在删除主要类别时删除所有子类别。 Example if i delete Outdoor then Cricket and Team A should be delete 例如,如果我删除“室外”,则应删除板球和A队

First of all think to change your categories structure to the Nested Set model . 首先,考虑将您的类别结构更改为嵌套集模型 It's better and esier to handle nested categories (and ant other structure). 处理嵌套的类别(和其他结构)更好,更容易。 Here is nice Laravel's package: 这是Laravel的好包装:

https://github.com/etrepat/baum https://github.com/etrepat/baum

For your example there is only not especially optimal solution. 对于您的示例,仅不是特别理想的解决方案。 When you willl query the leaf category: 当您查询叶子类别时:

$category = Categories::where('parent_id', $parent_id)
               ->orderBy('name', 'ASC')
               ->first();
return view({your view here}, compact('category'));

You'll need partial view (ex.: breadcrumb.blade.php ) with section: 您需要带有部分的局部视图(例如: breadcrumb.blade.php )。

<ul>
@section('breadcrumb')
@show
</ul>

The in the main action vie you can do somethink like that: 在主要动作中,您可以执行以下操作:

@section('breadcrumb')
    <li>{{$category->name}}</li>
@stop
@while($parent = $category->parent)
    @section('breadcrumb')
        @parent
        <li>{{$parent->name}}</li>
    @stop
@endwhile

ATTENTION 注意

But as I said in the begining - this is VERY sub-optimal solution because you have to call query for each parent, so it's only fine if you have not much nested levels. 但是正如我在开始时所说的那样-这是非常次优的解决方案,因为您必须为每个父级调用查询,因此只有在嵌套级别不多的情况下它才是好的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM