【问题标题】:Laravel 5 check if object exists and use if trueLaravel 5 检查对象是否存在,如果为真则使用
【发布时间】:2016-04-06 14:11:15
【问题描述】:

不用写了:

{{$x = $data->where('colour_id', 1)->where('size_id', 1)->where('product_id', 1)->first() ? $data->where('colour_id', 1)->where('size_id', 1)->where('product_id', 1)->first()->quantity : 0}}

有没有更清洁的方法?

【问题讨论】:

    标签: php laravel object laravel-5 blade


    【解决方案1】:

    对于 L5.1,有 pluck():

    {{ (int)$data->where(…)->pluck('quantity') }}
    

    对于 L5.2,有 value():

    {{ (int)$data->where(…)->value('quantity') }}
    

    【讨论】:

    • @limnote 这给了我:方法值不存在。 (查看:C:\wamp\www\brabiz\resources\views\stock-sheet-1.blade.php)
    【解决方案2】:

    您可以使用 Blade 的 or 语法:

    {{ $data->where('colour_id', 1)->where('size_id', 1)->where('product_id', 1)->first->quantity or 0 }}
    

    不知道你为什么要把它分配给$x,所以我删除了它,如果你确实需要它就读一下。

    不过,就个人而言,我会将其作为$data 对象是其实例的任何模型上的方法。 :)

    【讨论】:

      【解决方案3】:

      第一件事 - 你不应该在 Blade 中加载数据。

      在控制器中你应该这样做:

      $product = $data->where('colour_id', 1)->where('size_id', 1)->where('product_id', 1)->first();
      
      return view('sample.blade.php', compact('product'));
      

      现在在你的 Blade 文件中

      {{ $product ? $product->quantity : 0 }}
      

      【讨论】:

      • 我不能那样做,因为视图是静态的。
      猜你喜欢
      • 2020-12-20
      • 2019-09-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-06-09
      相关资源
      最近更新 更多