簡體   English   中英

如何使用 Laravel 實現類別子菜單中區域的計數?

[英]How do I achieve a count for regions in a sub menu of categories using Laravel?

我正在嘗試獲取某個類別下區域中的列表。

主頁上的區域菜單顯示了其區域中每個類別的所有列表的數量。 在類別頁面上,我試圖顯示在選定類別中有列表的地區的計數。

在我的清單 Model

 public function scopeInCategory($query, Category $category)
 {
    return $query->whereIn('category_id', [$category->id]);
 }

 public function region()
 {
    return $this->belongsTo(Region::class);
 }

在我的地區 model

 public function listings()
 {
    return $this->hasMany(Listing::class);
 }

在我的類別控制器中

class CategoryController extends Controller
{

    public function index(Category $category)
    {

        $regions = Region::with(['listings' => function($query) use ($category) {
        
            $query->inCategory($category);
        }])->first('region')->get();

       return view('categories.index', compact('regions'));
   }
}

在我的地區_dropdown.blade.php

 @foreach($regions as $region)
   
     <a class="dropdown-item" href="#">{{ $region->name }} 
    ( {{ $region->listings->count() }} )</a>
     
 @endforeach

但這不起作用區域菜單仍然顯示類別頁面上每個類別中所有列表的計數。

您可以使用 Eloquent 的withCount方法按特定Category獲取每個Region下的Listing計數,然后通過訪問 Eloquent 將為您初始化的listings_count屬性來訪問每個Regioncount數值。

class CategoryController extends Controller
{
    public function index(Category $category)
    {
       $regions = Region::withCount([
           'listings' => fn($q) => $q->where('category_id', $category->id)
       ])->get();
       return view('categories.index', compact('regions'));
   }
}

在你的blade文件中:

@foreach($regions as $region)
    <a class="dropdown-item" href="#">
        {{ sprintf('%s (%d)', $region->name, $region->listings_count) }}
    </a>
@endforeach

隨時要求任何澄清。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM