如果在对象

时间:2017-07-22 06:23:43

标签: php laravel laravel-5

我试图展示产品清单,并且我希望展示该产品的销售情况。

此处no_of_sellproduct_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出售)

4 个答案:

答案 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

https://laravel.com/docs/master/blade

了解详情

答案 1 :(得分:3)

 <h3 class="sale">{{ ($row->total_sells) ? $row->total_sells : '0' }} sales</h3>

http://php.net/manual/en/control-structures.if.php#102060

答案 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