深度嵌套在 Laravel 集合中的搜索值

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/42843687/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-14 15:34:53  来源:igfitidea点击:

Search value deeply nested within a Laravel Collection

laravellaravel-5eloquentlaravel-eloquent

提问by andcl

I have an Eloquent Collection just like this (dumped):

我有一个像这样的 Eloquent Collection(已弃用):

Collection {#788 ▼
  #items: array:3 [▼
    0 => Rating {#787 ▼
      #table: "ratings"
      +timestamps: false
      #connection: null
      #primaryKey: "id"
      #keyType: "int"
      #perPage: 15
      +incrementing: true
      #attributes: array:3 [▼
        "id" => 1
        "rating" => "50"
        "type" => "min"
      ]
      #original: array:3 [?]
      #relations: []
      #hidden: []
      #visible: []
      #appends: []
      #fillable: []
      #guarded: array:1 [?]
      #dates: []
      #dateFormat: null
      #casts: []
      #touches: []
      #observables: []
      #with: []
      #morphClass: null
      +exists: true
      +wasRecentlyCreated: false
    }
    1 => Rating {#786 ?}
    2 => Rating {#785 ?}
  ]
}

In one of my views, I need to show only the Ratings with 'max'type and I am trying to filter the collection without success until now. My tries so far:

在我的一个观点中,我只需要显示带有'max'类型的评级,并且直到现在我都试图过滤该集合但没有成功。到目前为止我的尝试:

if ($ratings && $ratings -> search('max') != false)

if ($ratings && $ratings -> search('max') != false)

OR

或者

if ($ratings && $ratings -> contains('max'))

if ($ratings && $ratings -> contains('max'))

So... What is the smart and eloquentway of achieving this?

那么......实现这一目标的明智而雄辩的方法是什么?

Thanks in advance.

提前致谢。

回答by Brian Glaz

You can use the wheremethod: https://laravel.com/docs/5.4/collections#method-where

您可以使用该where方法:https: //laravel.com/docs/5.4/collections#method-where

$filtered_ratings = $ratings->where('type', 'max');

回答by Yat23

You could also use the filter()method on the collection.

您也可以filter()在集合上使用该方法。

return $collection->filter(function ($value, $key) {
    if($value->type == 'max'){
      return $value;
    }    
});