我试图展示产品清单,并且我希望展示该产品的销售情况。
此处no_of_sell
有product_id
。问题是没有出售的产品,他们没有在no_of_sell中的id,所以在视图中显示空白空间。但我想显示0销售。我该如何展示?
$no_of_sells = \DB::table('products')
->leftJoin('buys','products.id','buys.product_id')
->select('products.id',DB::raw('COUNT(buys.product_id) as total_sells'))
->groupBy('products.id')
->where('buys.status','=','1')
->get();
查看部分:
@foreach($no_of_sells as $row)
@if($product->id == $row->id)
<h3 class="sale">{{$row->total_sells }} sales</h3>
@endif
@endforeach
(此处$product->id
包含列表中的所有产品,但$ row-&gt; id只包含购买表中的产品。如果匹配,则会打印no_of_sell但如果不匹配它应该打印0
出售)
答案 0 :(得分:3)
@foreach($no_of_sells as $row)
@if($product->id == $row->id)
<h3 class="sale">{{ $row->total_sells or '0' }} sales</h3>
@endif
@endforeach
了解详情
答案 1 :(得分:3)
<h3 class="sale">{{ ($row->total_sells) ? $row->total_sells : '0' }} sales</h3>
答案 2 :(得分:1)
使用以下代码:
@foreach($no_of_sells as $row)
@if($product->id == $row->id)
<h3 class="sale"> @if($row->total_sells > 0) {{$row->total_sells}} @else 0 @endif sales</h3>
@endif
@endforeach
答案 3 :(得分:0)
您还可以尝试使用三元运算符:
@foreach($no_of_sells as $row)
@if($product->id == $row->id)
<h3 class="sale">{{ ($row->total_sells > 0) ? $row->total_sells : '0'}} sales</h3>
@endif
@endforeach