【问题标题】:Check if values in collection has null value or not检查集合中的值是否具有空值
【发布时间】:2019-06-18 05:07:14
【问题描述】:

我有以下型号:

  1. Tour.php [belongsTo('App\Region'),belongsTo('App\TourCategory')]
  2. Region.php [hasMany('App\Tour');]
  3. TourCategory.php [hasMany('App\Tour', 'category_id');]

    以及执行以下任务的代码 sn-p:

  4. 通过它的蛞蝓找到旅游类别

  5. 获取具有该特定类别的游览
  6. 从这些旅行中获取所有独特的地区名称

      public function fetchByCategory($slug)
      {
       $category = TourCategory::where('slug','=', $slug)->first();
       $tours = $category->tours()->with('region')->get(['region_id']);
       $regions = $tours->pluck('region')->unique();
    
       return view('frontend.pages.travel-style')
       ->withResults($regions)
       ->withCategory($category);
      }
    

但是我创建的一些游览没有区域。没有区域存储游览时,默认设置空值。

这导致我的应用程序崩溃,因为我正在通过以下方式打印视图中的数据:

@foreach($results as $region)
    <div class="uk-width-1-2@s">
        <a href="{{ route('region2package',[$category->slug,$region->slug]) }}">
         <div class="uk-height-medium uk-flex uk-flex-center uk-flex-middle uk-background-cover uk-light" data-src="{{ asset($region->thumb) }}" uk-img>
        </a>
            <h3><a href="{{ route('region2package',[$category->slug,$region->slug]) }}">{{ $region->name }}</a></h3>
        </div>
    </div>
@endforeach
  1. 当我在上述方法中转储并死dd($tours-&gt;count());当数据库中只有一个旅游保存时没有区域它返回1
  2. 当我做dd($regions); 时,它给出了这个:

    Collection {#570 ▼
     #items: array:1 [▼
     0 => null
      ]
     }
    

如果有人能提出最好的方法来检查集合中的项目是否包含空值,我将非常感激?

【问题讨论】:

    标签: php laravel laravel-5.7


    【解决方案1】:

    您可以过滤您的集合,以便自动从您的集合中删除空值,而不是从集合中查找空值。

    $regions = $tours->pluck('region')->unique()->filter();
    

    【讨论】:

      【解决方案2】:

      我建议您在tours 关系上使用has 方法来仅获得region exists 的结果,如下所示:

      $tours = $category->tours()->has('region')->with('region')->get(['region_id']);
      

      【讨论】:

        猜你喜欢
        • 2020-05-12
        • 1970-01-01
        • 1970-01-01
        • 2017-06-04
        • 1970-01-01
        • 2014-02-17
        • 1970-01-01
        • 2011-04-24
        • 2014-09-17
        相关资源
        最近更新 更多