and*_*dcl 4 laravel eloquent laravel-5 laravel-eloquent
我有一个像这样的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 ?}
]
}
Run Code Online (Sandbox Code Playgroud)
在我的一个观点中,我只需要显示带有'max'类型的评级,我试图直到现在才过滤该集合而没有成功.到目前为止我的尝试:
if ($ratings && $ratings -> search('max') != false)
要么
if ($ratings && $ratings -> contains('max'))
那么...... 实现这一目标的聪明而有说服力的方法是什么?
提前致谢.
您可以使用以下where方法:https://laravel.com/docs/5.4/collections#method-where
$filtered_ratings = $ratings->where('type', 'max');
Run Code Online (Sandbox Code Playgroud)
filter()您还可以在集合上使用该方法。
return $collection->filter(function ($value, $key) {
if($value->type == 'max'){
return $value;
}
});
Run Code Online (Sandbox Code Playgroud)