【问题标题】:Laravel collection with if condition带有 if 条件的 Laravel 集合
【发布时间】:2018-01-14 06:38:36
【问题描述】:

我正在使用 laravel 集合 random 在单个帖子刀片中获取其他一些帖子,但问题是当我没有超过 6 个帖子时,我会收到错误 You requested 6 items, but there are only 1 items in the collection.

所以现在我需要做一个 if 语句来说明从 0 到 6 的随机帖子,这意味着例如如果我只有一个帖子并且我正在查看该帖子,那么忽略获取其他帖子(因为有没有其他帖子!),如果我总共有 2 个帖子,则只获得其他帖子,依此类推......直到随机顺序最多 6 个帖子。

这是我的功能:

public function show($slug) {
      $post = Post::where('slug', $slug)->firstOrFail();
      $postfeatures = Post::all()->random(6);
      $subcategories = Subcategory::with('posts')->get();
      $categories = Category::all();
      $advertises = Advertise::inRandomOrder()->where('status', '1')->first();
      return view ('frontend.single', compact('post', 'categories', 'subcategories', 'postfeatures', 'advertises'));
    }

这是我的看法:

<ul class="gallery">
   @foreach($postfeatures as $postss)
     <li><a data-toggle="tooltip" data-placement="top" title="{{ $postss->title }}" href="{{ route('frontshow', $postss->slug ) }}"><img src="{{ url('images/') }}/{{ $postss->image }}" class="img-responsive" alt="{{ $postss->title }}"></a></li>
   @endforeach
</ul>

谢谢。

【问题讨论】:

    标签: php laravel


    【解决方案1】:

    对于任何提出这个问题的人来说,接受的答案确实是一个沉重的追索权,它不适用于具有大量数据的现实项目。

    相反,您可以这样做:

    $builder = Post::query();
    $postFeatures = $builder
                     ->inRandomOrder()
                     ->when($builder->count() > 6, function ($query) {
                           return $query->limit(6)
                     })->get();
    

    这将确保 sql 只返回我们实际需要的内容,而不是记录中所有可能的帖子。

    【讨论】:

      【解决方案2】:

      你可以统计你的收藏

      $count = count(Post::all());
      if($count > 6){
      $postfeatures = Post::all()->random(6);
      }else{
      $postfeatures = Post::all()->random($count);
      }
      

      希望对您有所帮助!

      【讨论】:

      • 我知道,但这不是关于虚拟数据,而是关于问题(错误),当我的应用程序投入生产时,在线网站上不能有这个问题,我无法添加虚拟数据!
      • sr 我没有仔细阅读。请检查我更新的@RobertNicjoo
      猜你喜欢
      • 2014-03-23
      • 2021-08-26
      • 2016-01-23
      • 2015-03-19
      • 1970-01-01
      • 1970-01-01
      • 2021-07-25
      • 1970-01-01
      • 2015-08-24
      相关资源
      最近更新 更多