搜索值深深嵌套在Laravel Collection中

时间:2017-03-16 19:57:15

标签: laravel laravel-5 eloquent laravel-eloquent

我有一个像这样的Eloquent Collection(转储):

def index(conn, _params) do
  posts = Repo.all(from Post, order_by: [desc: :inserted_at])
  render(conn, "index.html", posts: posts)
end

在我的一个观点中,我只需要显示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 ▶} ] } 类型的评分,我试图直到现在才过滤该集合而没有成功。 到目前为止我的尝试:

'max'

OR

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

那么......实现这一目标的智能和雄辩的方式是什么?

提前致谢。

2 个答案:

答案 0 :(得分:5)

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

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

答案 1 :(得分:1)

您还可以在集合中使用filter()方法。

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