【问题标题】:How to get item from laravel eloquent collection by conditions?如何按条件从 laravel eloquent 集合中获取项目?
【发布时间】:2019-10-11 12:30:28
【问题描述】:

我使用 laravel eloquent 来获取给我收藏的帖子文件 但我想要一个按条件从该集合中获得的项目。 例如,从那个集合中,我想要一个 type = 'product' 的项目。

我正在使用 foreach 并检查每个符合我条件的项目并将其退回,但没有更好的方法吗?

我测试了像 contains 这样的收集方法,但它返回 null。

文件项的类型为“产品”或“博客”。

我的代码:

$post= Post::where('slug' , $slug)->first();

$cover = $post->files->contains(['type' , '=' , 'product']);

【问题讨论】:

  • 使用filter 方法。它在文档中。
  • $post->files 是关系吗?

标签: laravel collections eloquent


【解决方案1】:

使用集合filter方法。

$cover = $post->files->filter(function($file) {
    // show only the items that match this condition
    return collect(['product', 'blog'])->contains($file->type);
});

【讨论】:

    【解决方案2】:

    filter 方法使用给定的回调过滤集合,只保留那些通过给定真值测试的项目:

    $filtered = $post->files->filter(function ($value, $key) {
        return $value->type == 'product';
    });
    
    $filtered->all();
    

    Collections - filter()

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-06-26
      • 1970-01-01
      • 2021-09-08
      • 1970-01-01
      • 2017-04-23
      • 2015-06-24
      • 2014-07-11
      • 2016-06-23
      相关资源
      最近更新 更多