我正在使用集合过滤数据。但我需要使用类似的方法。我试过这样写:('name', 'LIKE', '%value%')
但它没有用。
这是我的方法:
protected function filterData(Collection $collection, $transformer) {
foreach (request()->query() as $query => $value) {
$attribute = $transformer::originalAttribute($query);
if (isset($attribute, $value)) {
$collection = $collection->where($attribute, $value);
}
}
return $collection;
}
答案 0 :(得分:6)
第一个问题是你是否真的知道自己在做什么。如果你从数据库中获取数据然后过滤它只是为了取一些元素它绝对不是最好的方法,因为你可以从数据库获取例如100000条记录,最终只有2个元素,它会杀死你的应用程序性能。
但是假设你真的想要使用支持集合进行过滤,那么就没有与LIKE一起使用,因为你只是过滤一个数组。如果你想使用类似于喜欢的东西而不是:
$collection = $collection->where('name', $value);
你可以使用:
$collection = $collection->reject(function($element) use ($value) {
return mb_strpos($element->name, $value) === false;
});
取决于您在集合中的实际内容而不是$element->name
,您可能需要使用$element['name']