[英]Laravel Model Count By Relationship
我有一个带有产品模型和ProductCategory模型的电子商务站点。 我目前在页面上通过“产品”模型显示产品,但希望能够获得当前模型中产品的所有类别列表以及每个类别中有多少产品。 我可以获得总数,但无法弄清楚如何获取显示的类别列表以及每个类别已返回多少结果。
产品型号
产品类别模型
目前,我使用...访问刀片中的结果
@foreach($products->chunk(3) as $row)
<div class="item-row">
@foreach($row as $product)
<div class="item item-thumbnail" style="height: 250px;">
<a href="product_detail.html" class="item-image">
@if(empty($product->Images{0}->original_image))
<img style="width: 100px; height: 100px;"
src="https://example.com/100x100/d3d3d3/fff.gif&text=No+Image"
alt="" />
@else
<img style="width: 100px; height: 100px;"
src="https://cdn.example.com.au/products/{{$product->id}}/{{$product->Images{0}->original_image}}"
alt="" />
@endif
</a>
<div class="item-info">
<h4 class="item-title">
<a href="/store/{{$category->alias}}/{{$product->alias}}">
{{$product->product_name}}
</a>
</h4>
<p class="item-desc"> </p>
@if(empty($product->special_price))
<div class="item-price">
${{$product->normal_price}}
</div>
@else
<div class="item-price">
${{$product->special_price}}
</div>
<div class="item-discount-price">
${{$product->normal_price}}
</div>
@endif
</div>
</div>
@endforeach
</div>
@endforeach
并希望能够生成所有类别的列表,其中产品显示为...
@foreach($products->categories as $category)
<li>
{{$category->category_name}} ({{$category->count}})
</li>
@endforeach
全部来自同一模型。
如果可以帮助澄清,我不希望模型发生巨大变化,因为我仍然希望能够像目前那样从刀片模板访问模型中的产品,但也希望能够提取类别列表例如下面的示例...
| Product_ID | Product_Name | Category_ID |
| ---------- | ------------ | ----------- |
| 1 | Product 1 | 1 |
| 2 | Product 2 | 1 |
| 3 | Product 3 | 2 |
| Category ID | Category Name |
| ----------- | ------------- |
| 1 | Category 1 |
| 2 | Category 2 |
然后在我的页面上显示下表,以显示结果中显示的产品类别...
| Category Name | # Products |
| ------------- | ---------- |
| Category 1 | 2 |
| Category 2 | 1 |
如果您提供查询产品和类别的代码,那将非常有帮助。
但实际上这是您需要做的。 您需要使用->withCount(..)
:
$products = Product::with([
'categories' => function ($query) {
// Adds count of category-related products
$query->withCount('products as count');
},
])->get();
然后这将在您看来有效:
@foreach($products as $product)
@foreach($product->categories as $category)
<li>{{$category->category_name}} ({{$category->count}})</li>
@endforeach
@endforeach
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.