[英]Get all parents from a subcategory
I have a table 我有桌子
id; name; parent_id
1 xxx 0
2 ccc 0
3 zzz 1
4 yyy 3
My goal is to get the category and get all the parents exemple: 我的目标是获取类别并让所有父母成为示例:
Category with id 4 编号为4的类别
1.xxx
3.zzz
4.yyy
What i have done until now my model Categories 到目前为止,我所做的是我的模型
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');
}
}
My controler that gets the category i want: 我的控制器得到我想要的类别:
$data['cat']= Categories::with('parent')->get();
my blade 我的刀片
@foreach ($cat as $c)
{{ $c->name }}
@endforeach
I am a bit confused how to do this i have try for 2 days find tutorials and read other examples but i can't understand i am a bit noob i am sorry. 我有点困惑如何做到这一点,我已经尝试了2天,找到了教程并阅读了其他示例,但是我不明白我有点菜鸟,对不起。
Thanks for the help 谢谢您的帮助
Relations: 关系:
public function parent()
{
return $this->belongsTo(Category::class, 'parent_id');
}
public function children()
{
return $this->hasMany(Category::class, 'parent_id');
}
Starting with parent categories: 从父类别开始:
$parentCategories = Category::where('parent_id', '=', 0)->with('children')->get();
In view: 鉴于:
@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
Starting with child categories: 从子类别开始:
$childCategories => Category::where('parent_id', '!=', 0)->with('parent')->get();
In view: 鉴于:
@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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.