从子类别中获取所有父母

时间:2019-08-22 12:15:18

标签: php sql laravel

我有一张桌子

id; name; parent_id
1   xxx   0

2   ccc   0

3   zzz   1

4   yyy   3

我的目标是获取类别并让所有父母成为示例:

ID为4的类别

1.xxx

 3.zzz

   4.yyy

到目前为止,我所做的是我的模型类别

class Categories extends Model

{
    protected $table = 'categories';

    public function parent() {
       return $this->hasMany('App\Models\Categories','id');   
    }

    public function children(){
       return $this->hasMany('App\Models\Categories','parent_id');   
    }

}

我的控制器获得了我想要的类别:

   $data['cat']= Categories::with('parent')->get();

我的刀片

@foreach ($cat as $c)
   {{ $c->name }}
 @endforeach

我有点困惑,我已经尝试了2天,找到了教程并阅读了其他示例,但我不明白我有点菜鸟,很抱歉。

感谢您的帮助

1 个答案:

答案 0 :(得分:0)

关系:

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

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

从父类别开始:

$parentCategories = Category::where('parent_id', '=', 0)->with('children')->get();

视图中:

@if($parentCategories)
<div class="categories">
    @foreach($parentCategories as $parent)
        ...
        @if($parent->children())
            ...
            @foreach($parent->children as $child)
                ...
                @if($child->children())
                    ...
                        @foreach($child->children as $c)
                            ...
                        @endforeach
                    ...
                @endif
                ...
            @endforeach
            ...
        @endif
        ...
    @endforeach
</div>
@endif

从子类别开始:

$childCategories => Category::where('parent_id', '!=', 0)->with('parent')->get();

视图中:

@if($childCategories)
<div class="categories">
    @foreach($childCategories as $child)
        <div>{{ $child->name }}</div>

        @if($child->parent)
            <div style="padding-left: 5px;">{{ $child->parent->name }}</div>

            @if($child->parent->parent)
                <div style="padding-left: 10px;">{{ $child->parent->parent->name }}</div>
            @endif
        @endif
    @endforeach
</div>
@endif