2017-10-04 52 views
1

我在頁面上有父類別和子類別。我想要做的是當沒有產品,並且某些父類別中沒有分配的子類別不會顯示在頁面上時。不要在Laravel中顯示空父類別

所以我有這樣的分類模型

public function item() 
{ 
    return $this->hasMany('Item','category_id'); 
} 

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


public function getCategories() 
{ 
    $categoires = Category::where('parent_id',0)->get(); 
    $categoires = $this->addRelation($categoires); 
    return $categoires; 
} 

public function selectChild($id) 
{ 
    $categoires = Category::where('parent_id',$id)->where('published', 1)->get(); 
    $categoires = $this->addRelation($categoires); 
    return $categoires; 
} 

這在控制器

public function index() 
{ 
    $Category = new Category; 
    $allCategories = $Category->getCategories(); 
    return view('frontend.home', compact('allCategories', 'unviewedMessagesCount')); 
} 

這對葉片視圖

@foreach($allCategories as $category) 
    {!!$category->title!!} ({!! $category->itemCount!!}) 
    <p class="card-text"> 
     @foreach($category->subCategory as $subcategory) 
     {!!$subcategory->title!!} {!! $subcategory->itemCount !!} 
     @endforeach 
    </p> 
    <a href="{!!route('list',array($category->id))!!}" class="btn btn-primary">View Category</a> 
@endforeach 

這是在類別中的記錄樣本表中有列

id | title  | parent 
1 Main cat  0 
2 Sub-Cat  1 
3 Sub-Cat 2 1 
4 Main cat 2 0 

因此每個親本是0,並且每個子(子類)具有父ID

item表也參照category表 - >列category_id

我不能計算出來如何如果沒有項目,並且沒有孩子,則不要在頁面上顯示它。

+1

你可以做這樣的'$依種類=類別::有( '孩子') - >有( 'children.item') - >在哪裏('PARENT_ID ',0) - > get();' – Maraboc

+0

@Maraboc,謝謝,但未找到列錯誤'SQLSTATE [42S22]:找不到列:1054'where子句'中的未知列'pare nt_id' – Ivan

回答

2

在控制器

$allCategories = Category::where('parent_id', 0)->has('children.item') 
       ->with(['children'=> function($query){ 
        $query->withCount('item'); 
       }]) 
       ->get() 
       ->each(function($parentCategory){ 
        // if you wants calculate sum child category item count and assign to parent category item_count. 
        $parentCategory->item_count = $parentCategory->children->sum(function ($child) { return isset($child->item_count)?$child->item_count:0;}); 
       }); 
return view('frontend.home', compact('allCategories')); 

在此查詢中只有一個查詢將被執行,並返回您的所有需求。

並在刀片查看文件

@foreach($allCategories as $category) 
    {!!$category->title!!} ({!! $category->item_count!!}) 
    <p class="card-text"> 
    @foreach($category->children as $subcategory) 
     {!!$subcategory->title!!} {!! $subcategory->item_count !!} 
    @endforeach 
    </p> 
    <a href="{!!route('list',array($category->id))!!}" class="btn btn-primary">View Category</a> 
@endforeach 
+0

感謝回答併爲延誤抱歉。我沒有找到'Class'Item' – Ivan

+0

對不起,這是錯誤:'找不到列:'字段列表'中的1054未知列'children.item_count'(SQL:select sum(' children'.'item_count')作爲來自'categories'的聚合)' – Ivan

+0

代碼已更新。所以請嘗試最新的一個 –

相關問題