問題描述
使用 Laravel 5.1,我嘗試從 MySQL 類別表創建菜單列表.我的服務提供者返回數據,但我不明白如何在 foreach 循環中創建子類別.當我執行循環時,只返回子查詢的最后一行.任何指導將不勝感激.
Using Laravel 5.1, I am trying to create a menu list from a MySQL categories table. My service provider returns data, but I don't understand how to create the child categories in a foreach loop. When I perform the loop, only the last row of the child query is returned. Any guidance would be appreciated.
類別表
id | cat_name | cat_parent_id
--- | --------------| -------------
1 | Parent Cat 1 | NULL
2 | Parent Cat 2 | NULL
3 | Child Cat 1 | 2
4 | Child Cat 2 | 2
5 | Parent Cat 3 | NULL
6 | Child Cat 3 | 5
預期結果
Parent Cat 1
Parent Cat 2
Child Cat 1
Child Cat 2
Parent Cat 3
Child Cat 3
viewComposerServiceProvider.php
public function boot()
{
$this->composeTopCategoryNavigation();
$this->composeSubCategoryNavigation();
}
private function composeTopCategoryNavigation()
{
view()->composer('partials.header', function($view)
{
$view->with('top_cats', Category::whereNull('cat_parent_id')->orderBy('cat_name', 'asc')->get());
});
}
private function composeSubCategoryNavigation()
{
view()->composer('partials.header', function($view)
{
$view->with('sub_cats', Category::whereNotNull('cat_parent_id')->orderBy('cat_name', 'asc')->get());
});
}
標題視圖
<ul>
@foreach ($top_cats as $top_cat)
<?php $top_cat_slug = str_slug( $top_cat->cat_name, "-"); ?>
<li>{{ $top_cat->cat_name }}
@foreach ($sub_cats as $sub_cat)
@if ( $sub_cat->cat_parent_id === $top_cat->id )
<ul>
<li{{ $sub_cat->cat_name }}</li>
</ul>
@endif
@endforeach
</li>
@endforeach
</ul>
推薦答案
首先,你的做法是低效的.您的視圖遍歷每個父類別的所有子類別.如果您正確定義關系并利用 Eloquent 的預先加載,您可以更輕松地獲取和訪問子類別.
First of all, what you are doing is inefficient. Your view iterates through all subcategories for every parent category. If you defined relations properly and made use of Eloquent's eager loading, you could fetch and access child categories in easier way.
從定義關系開始:
class Category extends Model {
//each category might have one parent
public function parent() {
return $this->belongsToOne(static::class, 'cat_parent_id');
}
//each category might have multiple children
public function children() {
return $this->hasMany(static::class, 'cat_parent_id')->orderBy('cat_name', 'asc');
}
}
一旦您正確定義了關系,您就可以獲取整個類別樹,如下所示:
Once you have the relations defined properly, you can fetch whole category tree like below:
view()->composer('partials.header', function($view) {
$view->with('categories', Category::with('children')->whereNull('cat_parent_id')->orderBy('cat_name', 'asc')->get());
});
不需要第二個作曲家,因為父類別已經包含子類別.
The second composer won't be needed, as parent categories already contain children.
現在,您只需要在視圖中顯示類別:
Now, you only need to display the categories in your view:
<ul>
@foreach ($categories as $parent)
<li>{{ $parent->cat_name }}
@if ($parent->children->count())
<ul>
@foreach ($parent->children as $child)
<li>{{ $child->cat_name }}</li>
@endforeach
</ul>
@endif
</li>
@endforeach
</ul>
這篇關于Laravel 在同一個表中返回父母的孩子的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!